How to Validate This Select Option If Not Selected

How do I validate this select option if not selected?

You could add a disabled and selected option to your select for the required to work properly, forcing the user to explicitly select one option first:

<form>  <select class="form-control required" name="jk" id="gender" required>    <option disabled selected></option>    <option>Pilih</option>    <option value="Laki-Laki">Laki - Laki</option>    <option value="Perempuan">Perempuan</option>  </select>  <input type="submit"></form>

How to validate same option selected and adding disable

You would have to:

  • actually disable the option element corresponding the value just added,
  • make sure the option element, though disabled, is no longer selected

    $("#all-employees option").filter(function() { //find the value just added
    return $(this).text() == text;
    })
    .prop('disabled', true) //disable the option element
    .end().parent().val(''); //reset the select element

Set up a new event listener as follows:

    //set up a new event listener for deleting (jQuery)
$(document).on('click', '.minus-icon', function() {
//get the option value
var value = $(this).closest('.emp-item').data('value');console.log( value );

//perform deletion
$(this).closest('.emp-item').remove();

//enable the corresponding option element
//start by finding the element
$('#all-employees option').filter(function() {
return this.value === value;
})
//now enable the element
.prop('disabled', false)
//then 'reset' the select element
.end().parent().val('');
});

var employeeAdd = document.querySelector('.plus-icon');
if(employeeAdd) { employeeAdd.addEventListener('click', addAssignee);}
function addAssignee(){ var x = document.getElementById('all-employees').value; var text = $("#all-employees option:selected").text();
var y = $(".added-employees").find('.emp-item').val();
if(x != y) { $(".added-employees").append("<div class='emp-item' data-value='" + x + "'>" + text + "<i class='fa fa-minus-square minus-icon'></i></div>"); $("#all-employees option").filter(function() { return $(this).text() == text; }).prop('disabled', true).end().parent().val(''); }else{ alert('Already Added'); }}
//set up a new event listener for deleting (jQuery)$(document).on('click', '.minus-icon', function() { //get the option value var value = $(this).closest('.emp-item').data('value'); //perform deletion $(this).closest('.emp-item').remove(); //enable the corresponding option element //start by finding the element $('#all-employees option').filter(function() { return this.value === value; }) //now enable the element .prop('disabled', false) //then 'reset' the select element .end().parent().val('');});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div class="assign-dropdown">                    <select id="all-employees">                        <option disabled selected value="">All Employees</option>                        <option value="one">Saman</option>                        <option value="two">sunil</option>                        <option value="three">Shantha</option>                    </select>
<div class="plus-icon"> <i class="fa fa-plus-square"></i> </div>
<div class="added-employees">
</div> </div><link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">

How to validate select dropdown value is not empty from external javascript file?

The good news is that you're really close to having a working solution!

There was only two problems with the javascript you posted above:

the first is that the default value of your mySelect element is actually "selectstate" so you should really check to see if mySelect.value === "selectstate.

Another issue is that in this section you have a condition that would shortcircuit your validation:

    // gender validation
if (document.themissing.gender[0].checked == true) {
return true;
}
else if (document.themissing.gender[1].checked == true) {
return true;
}
else {
alert("Gender must be selected!");
return false;
}

So if either of the gender checkboxes are selected then the whole form is considered valid even if no state has been selected!

I would change the code like this:

function validateForm() {
// name validation
var myName = document.forms["themissing"]["name1"].value;
if (myName == "") {
alert("Name must be filled out!");
return false;
}

// age validation
var myAge = document.forms["themissing"]["age1"].value;
if (myAge == "") {
alert("Age must be filled out!");
return false;
}

// gender validation
if (document.themissing.gender[0].checked == false && document.themissing.gender[1].checked == false) { // <-- second change here (first two ifs replaced by one check that can only fail)
alert("Gender must be selected!");
return false;
}

// dropdown validation
var mySelect = document.getElementById("states");
if(mySelect.value === "selectstate) { // <-- first change here
alert('You must select a State!');
return false;
}
console.log("there is a value");
return true;

}

How to enable validation of select option hide/show div-input only when it selected?

This may help.

in JQUERY:

Validate only if others is selected.

var inquiry_type = $('#inquiry_type').val();
else if (inquiry_type === 'others' && !inquiry_other_subj.match(/^(?=.*[A-Za-z ]).{5,20}$/)) {
alert("Need to enter a proper inquiry title containing only letter!");
}

Add the other_msg_subjparameter in the variable parameters only if others is selected.

var parameters = "......"; //Other parameters
if(inquiry_type == "others")
{
parameters = parameters + "&other_msg_subj="+inquiry_other_subj;
}

in PHP:

Check if only the parameter is present

else if(!isset($_POST['other_msg_subj']) && !preg_match ('%^[A-Za-z\.\' \-]{2,30}$%', $_POST['other_msg_subj']))
{
echo "Please enter a valid message subject title!";
exit();
}

Also (Just a suggestion) you can simplify the JQUERY code :

show/hide as toggle(true/false)
true = show(), false = hide()

$(function() {
$('#other_subj').hide();
$('#inquiry_type').change(function(){
var display = $('#inquiry_type').val() === 'others';
$('#other_subj').toggle(display);
});
});

How to validate one dropdown if the other dropdown is not selected and vice versa?

scenario to achieve: if one dropdown is selected then I want the form to be submitted irrespective of second dropdown selected or not.

You would want the require_from_group method, which is part of the Additional Methods file. This rule, when properly assigned to both select elements, would simply ensure that at least one is selected.

I would construct a working demo, but you have not shown us any of your HTML.

  1. You need to remove the required class as that will force the required rule and over-ride your depends. In the case of mine, it adds the required rule, which we do not want here.

  2. Using the rules object, you must target the field's name, not the id.

  3. Finally, instead of depends, you can use the require_from_group method to ensure only one select is required out of the two.

DEMO: jsfiddle.net/376otgfL/

$('#feed_form').validate({ // initialize the plugin
rules: {
'list_country[]': { // <- NAME, not id
require_from_group: [1,".multi_select"]
},
'list_site[]': { // <- NAME, not id
require_from_group: [1,".multi_select"]
},
list_trend: { // <- NAME, not id
required: true
}
},
ignore: ":hidden:not(select)"
});

How to validate the select method with submit type?

You can call a function on clicking the button. Inside the function get the text of the selected option:

function getValue(){  var el = document.querySelector('.temp');  var val = el.options[el.selectedIndex].text;  var t;  if(val == "Volvo")    t = 'val11';  else if(val == "Saab")    t = 'val14';  if(val == "Opel")    t = 'val82';  else if(val == "Audi")    t = 'val34';  alert(t);}
<form>  <select name="carlist" class="temp">    <option value="10">Volvo</option>    <option value="20">Saab</option>    <option value="30">Opel</option>    <option value="45">Audi</option>  </select>
<input onclick="getValue()" type="submit" class="temp" value="submit the answer"></form>

Validate select Input fields based on what is selected in option menu

There were few issues that you need to take care of -

1) the form tag closing should also include the submit button.

2) If you're using that button to submit the form, then add type="submit" as an attribute to the form.

check this fiddle for the validation - https://jsfiddle.net/8o0smzth/3/

I have commented out some of part of your code. Please don't hesitate to ask if you have more questions.

Angular 6 or 2+ form validation for select option not being validated

Your code looks perfect. I also faced this issue. At that time it was class issue. Just try to remove class as below.

<div *ngIf="submitted && f.invoice_type.errors">    // Remove class from hear 
<div *ngIf="f.invoice_type.errors.required">Invoice type is required</div>
</div>

At that time I did not add any css for that class. And after remove that class it worked for me. So I think this might be the same issue.

And make sure you have to put <select> in <form> tag.

Hope it helps you :)

Select Required validation not working in form

The following is from w3 docs:

The required attribute is a boolean attribute. When specified, the
user will be required to select a value before submitting the form.

...

if the value of the first option element in the select element's
list of options (if any) is the empty string

...

Which means that the required attribute works only if the value of the first element is empty



Related Topics



Leave a reply



Submit