The name of my select option property is populated dynamically.
On submit my form I need to know if all my forams selects filled ...
How can I do this?
I would also like to take the mouse cursor to the select that was not filled.
<script type="text/javascript" src="js/jquery-1.6.4.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#teste").click(function () {
a = $("select[name='sel[]'] option:selected").length;
alert(a);
});
});
</script>
<title>
</title>
</head>
<form>
<select name="sel[0]">
<option value="teste"></option>
<option value="teste">1234</option>
<option value="teste">1234</option>
<option value="teste">1234</option>
</select>
<br />
<br />
<br />
<select name="sel[1]">
<option value="teste"></option>
<option value="teste">1234</option>
<option value="teste">1234</option>
<option value="teste">1234</option>
</select>
... Many others
<input type="button" id="teste" value="TESTAR">
</form>
</html>
Give your default option a value of -1 and provide a common class name for these options(Which is efficient that attribute starts with selector).
Try:
HTML:
<form>
<select name="sel[0]" class="sel">
<option value="-1"></option>
<option value="teste">1234</option>
<option value="teste">1234</option>
<option value="teste">1234</option>
</select>
<br />
<br />
<br />
<select name="sel[1]" class="sel">
<option value="-1"></option>
<option value="teste">1234</option>
<option value="teste">1234</option>
<option value="teste">1234</option>
</select>
<input type="button" id="teste" value="TESTAR">
JS:
$(document).ready(function () {
$("#teste").click(function () {
$(".sel").each(function () {
if (this.value == -1) { //If you are not providing value check for this.selectedIndex == 0
$(this).focus(); //set the focus
return false; //and break out of the loop
}
});
});
});
Fiddle
You have to set the variable like this var a;.
There is no element with select[name='sel[]'], you have a number inside of it, you could use name*= or name^= to say name contains or name starts with sel respectively
JSFIDDLE DEMO
$("#teste").click(function () {
var a = $("select[name^='sel'] option:selected");
var count = 0;
$.each(a, function () {
if ($(this).text().length) {
count++;
}
});
alert(count);
});
Select acts like the usual input when submitting form. So you can find selects with empty value:
$("select[value=]").first().focus()
Or iterate over all form elements, checking its value and type.
http://jsbin.com/UduNaGOh/1/edit?html,output
$(document).ready(function () {
$("#teste").click(function () {
var test = true;
$("#myform select").each(function(){
var select = $(this);
if(select.val() == 'none') {
select.addClass('fail');
select.focus();
test = false;
} else {
select.removeClass('fail');
}
});
if(test){
alert('well done');
$("#myform select").removeClass('fail');
// do your send stuff ...
}
});
});
I'm changing the class to style the empty selects.
So here is the css:
#myform > select.fail { background: red }
If you just need the number of empty selects you can use:
$('select:has(option[value="none"]:selected)').length
Related
I have 3 form select drop downs and have successfully retained the first select value after page loads, but am unable to get the second and third select values to be retained.
I'm using JavaScript and Jquery only for this.
I've tried over and over and finally got to bring my code here to see if someone more advanced can point out what I'm not doing correctly.
<form id="form">
<select id="select0" type="text">
<option type="text" value="" >make</option>
<option type="text" value="ford" >ford</option>
</select>
<select id="select1" type="text">
<option type="text" value="" >model</option>
<option type="text" value="mustang" >mustang</option>
</select>
<select id="select2" type="text">
<option type="text" value="">year</option>
<option type="text" value="1967" >1967</option>
</select>
<input type="submit" value="go">
</form>the
// JavaScript
var storeMake = sessionStorage.getItem("themake");
var storeModel = sessionStorage.getItem("themodel");
var storeYear = sessionStorage.getItem("theyear");
var make = $("#form #select0");
var model = $("#form #select1");
var year = $("#form #select2");
if(storeMake != undefined || storeMake != null){
make.find(":selected").removeAttr("selected");
make.find("option").each(function () {
if ($(this).val() == storeMake) {
$(this).attr("selected", true);
}
});
}
if(storeModel != undefined || storeModel != null){
model.find(":selected").removeAttr("selected");
model.find("option").each(function () {
if ($(this).val() == storeModel) {
$(this).attr("selected", true);
}
});
}
if(storeYear != undefined || storeYear != null){
year.find(":selected").removeAttr("selected");
year.find("option").each(function () {
if ($(this).val() == storeYear) {
$(this).attr("selected", true);
}
});
}
make.change(function () {
sessionStorage.setItem("themake", make.val());
});
model.change(function () {
sessionStorage.setItem("themodel", model.val());
});
year.change(function () {
sessionStorage.setItem("theyear", year.val());
});
The jQuery .val() method can be used to set the value of a select. This will replace each if statement.
Try the code below. The snippet will not work in Stack Overflow because sessionStorage is disabled.
var storeMake = sessionStorage.getItem("themake"),
storeModel = sessionStorage.getItem("themodel"),
storeYear = sessionStorage.getItem("theyear");
$("#select0").val(storeMake).change(function () {
sessionStorage.setItem("themake", $(this).val());
});
$("#select1").val(storeModel).change(function () {
sessionStorage.setItem("themodel", $(this).val());
});
$("#select2").val(storeYear).change(function () {
sessionStorage.setItem("theyear", $(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form">
<select id="select0">
<option value="">make</option>
<option value="ford">ford</option>
</select>
<select id="select1">
<option value="">model</option>
<option value="mustang">mustang</option>
</select>
<select id="select2">
<option value="">year</option>
<option value="1967">1967</option>
</select>
<input type="submit" value="go">
</form>
A few added notes:
The type attribute is not needed on select or option elements.
$("#form #select0") can updated to $("#select0") since the id will be unique. Same with select1 and select2.
My jquery code is having two dropdown boxes,one containing country and the other one holds currency.so here i want that whenever a country is selected in the box it will trigger a change function that will perform some comparison using if-else and will select the currency in the other dropdown and leaving it as 'disabled' to true.Below is my code for the same:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function () {
$(".select").change(function () {
debugger;
var c = $('#country :selected').text();
if (c == 'india') {
$('select[name="currency"]').find('option[value="1"]').attr("selected", true);
document.getElementById('disable').disabled = true;
}
else
{
$('select[name="currency"]').find('option[value="2"]').attr("selected", true);
document.getElementById('disable').disabled = true;
}
});
});
//$(function () {
// var select = $('select.select');
// select.change(function () {
// select.not(this).val(this.value);
// document.getElementById("disable").disabled = true;
// });
//});
</script>
</head>
<body>
<form>
<select name="country" id="country" class="select">
<option value="">Select</option>
<option value="1">india</option>
<option value="2">America</option>
</select>
<select name="currency" id="disable" class="select">
<option value="">Select</option>
<option value="1">INR</option>
<option value="2">DOLLAR</option>
</select>
<br><br>
</form>
</body>
</html>
but now the problem is when i select india it shows IR which is ok and then when i select America,it shows Doller and finally the problem comes now,when i again change the country back to india the change function is not called at all and dollar gets remain selected and disabled.Fix this it would be a great help!
Use .prop instead of .attr
With .attr, both the options have selected attribute set hence browser fail to make out which option to be set as selected.
From docs, To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method. (.attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior.)
$(document).ready(function() {
$(".select").change(function() {
var c = $('#country :selected').text();
if (c == 'india') {
$('select[name="currency"]').find('option[value="1"]').prop("selected", true);
} else {
$('select[name="currency"]').find('option[value="2"]').prop("selected", true);
}
document.getElementById('disable').disabled = true;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form>
<select name="country" id="country" class="select">
<option value="">Select</option>
<option value="1">india</option>
<option value="2">America</option>
</select>
<select name="currency" id="disable" class="select">
<option value="">Select</option>
<option value="1">INR</option>
<option value="2">DOLLAR</option>
</select>
<br>
<br>
</form>
Since the values on both select are the same. You can easily set the value of the second select based on the first.
$(function() {
$('.select').on('change',function() {
var val = $(this).find(':selected').val();
$('[name=currency]').val( val ).attr('disabled',true);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<select name="country" id="country" class="select">
<option value="">Select</option>
<option value="1">india</option>
<option value="2">America</option>
</select>
<select name="currency">
<option value=""> </option>
<option value="1">INR</option>
<option value="2">DOLLAR</option>
</select>
</form>
To complete the above answer you can use the "$" jquery selector instead of document.getElementById
Plus note you can use .prop('disabled', false);
too, like this :
$(document).ready(function() {
$(".select").change(function() {
var c = $('#country :selected').text();
if (c == 'india') {
$('select[name="currency"]').find('option[value="1"]').prop("selected", true);
} else {
$('select[name="currency"]').find('option[value="2"]').prop("selected", true);
}
$(#'disable').prop('disabled', true);
});
});
I need the submit button to be active only if all the fields and filled/selected.
I saw a couple of examples but don’t know how to do it!!
$(document).ready(function()
{
$('.envia').prop('disabled',true);
$('#matricula').on('change', function ()
{
$('#envia').prop('disabled', !$(this).val());
}).trigger('change');
});
$(document).ready(function()
{
$('.envia').prop('disabled',true);
$('#peca').on('change', function ()
{
$('#envia').prop('disabled', !$(this).val());
}).trigger('change');
});
$(document).ready(function()
{
$('.envia').prop('disabled',true);
$('#quilometros').keyup(function()
{
$('#envia').prop('disabled', !$(this).val());
}).trigger('change');
});
$(document).ready(function()
{
$('.envia').prop('disabled',true);
$('#data').keyup(function()
{
$('#envia').prop('disabled', !$(this).val());
}).trigger('change');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form action="#">
<select id="matricula">
<option></option>
<option value="1">Matricula 1</option>
<option value="2">Matricula 2</option>
</select>
<select id="peca">
<option></option>
<option value="1">Peca 1</option>
<option value="2">Peca 2</option>
</select>
<input type="text" id="quilometros">
<input type="text" id="data">
<input type="submit" id = "envia" value="ok"></input>
</form>
This help you :
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
window.onload = fun;
function fun(){
var matr = $("#matricula").val();
var peca = $("#peca").val();
var txt1 = $("#data").val();
var txt2 = $("#quilometros").val();
if(matr.length==0 || peca.length==0||txt1.length==0||txt2.length==0)
$("#envia").prop("disabled",true);
else
$("#envia").prop("disabled",false);
}
</script>
<form action="#">
<select id="matricula" onchange="fun()">
<option></option>
<option value="1">Matricula 1</option>
<option value="2">Matricula 2</option>
</select>
<select id="peca" onchange="fun()">
<option></option>
<option value="1">Peca 1</option>
<option value="2">Peca 2</option>
</select>
<input type="text" id="quilometros" oninput="fun()">
<input type="text" id="data" oninput="fun()">
<input type="submit" id = "envia" value="ok">
</form>
</body>
</html>
The problem you have is you are setting disabled based on individual fields without checking the state of all the others.
you can use one event handler for all but you also need to check all controls each time
$(function(){
// pseudo selector `:input` will match all form controls
var $inputs = $('#form-id :input').on('change input',validate);
function validate(){
var inValid = $inputs.filter(function(){
return !this.value;
}).length;
$('#envia').prop('disabled', inValid );
}
// also call function on page load
validate();
});
Here I'm using filter() to check length of element collection where value is not set
So, I have 2 events attached to several select elements. A click event and a change event. When the user selects an option, I keep track of previously selected options on a JS object to tell the user that the option is already used and can't be reused and reset that select to the default value. If the select had a previous value that is not default, I remove the property from the object. Now, on each click event, I would have a JS variable give me the value of that select before the change happens. But, because of the difference in order of events been trigger (Firefox and Chrome) for example, in one I get the default which was when it reset, and the other I get the value right before the reset.
HTML:
<html>
<head>
<title>Objects test on Browsers</title>
</head>
<body>
<div class="container">
<select name="dd1">
<option value="0">-Select-</option>
<option value="cat">cat</option>
<option value="dog">dog</option>
<option value="bear">bear</option>
</select>
<br />
<br />
<select name="dd2">
<option value="0">-Select-</option>
<option value="cat">cat</option>
<option value="dog">dog</option>
<option value="bear">bear</option>
</select>
<br />
<br />
<select name="dd3">
<option value="0">-Select-</option>
<option value="cat">cat</option>
<option value="dog">dog</option>
<option value="bear">bear</option>
</select>
<br />
<br />
</div>
</body>
</html>
JavaScript:
var alreadyUsed = {};
var prevField = "";
$(function() {
// Events for drop downs
$("select[name^='dd']").on("focus", function(event) {
prevField = $(this).val();
console.log(prevField);
}).on("change", function(event) {
var fieldInUsed = checkNotUsedAlready("fields", $(this).val());
if (fieldInUsed === true) {
delete alreadyUsed[prevField];
$(this).val(0);
} else {
var selectField = $("select[name='" + event.target.name + "']" + " option:selected");
if (selectField.html() != "-Select-") {
alreadyUsed[selectField.html()] = $(this).val();
} else {
delete alreadyUsed[prevField];
}
}
});
});
function checkNotUsedAlready(type, value) {
var fieldColInUse = false;
if (type == "fields") {
for (var prop in alreadyUsed) {
if (alreadyUsed.hasOwnProperty(prop)) {
if (prop == value) {
fieldColInUse = true;
alert("Field is already in use.\nPlease, select a different field.");
break;
}
}
}
} else if (type == "columns") {
for (var prop in alreadyUsed) {
if (alreadyUsed.hasOwnProperty(prop)) {
if (alreadyUsed[prop] == value) {
fieldColInUse = true;
alert("Column is already in use.\nPlease, select a different column or custom.");
break;
}
}
}
}
return fieldColInUse;
}
I select cat on first drop down. Object now is Object{cat:"cat"}
I select dog on second drop down. Object is now Object {cat:"cat", dog:"dog"}
I select cat on second drop down.
At this point, firefox returns me dog as the previous value, which is what I want, but Chrome returns me zero because of the reset and when it set the value because of the events triggering order. Any ideas how can I deal with this in a different way?
One of the reasons for the JS object is that I need to have a list of which values are used to submit later and which are not used yet. A value needs to be unique.
NOTE: Choose cat for Drop down 1, dog for Drop down 2 and bear for Drop Down 3. Then, choose dog from Drop Down 1. On chrome, it will delete bear but on Firefox, it will delete cat.
Thanks in advance.
Maybe it would help to simplify things a bit. This works for me in Chrome, IE 9+, and Firefox:
var alreadyUsed = [];
$(document).ready( function() {
$("select[name^='dd']").data("previous","0");
$("select[name^='dd']").on("change", function(event) {
var newValue = $(this).val();
var prevValue = $(this).data("previous");
if(alreadyUsed.indexOf(newValue) == -1){
if(prevValue != "0") alreadyUsed.splice( alreadyUsed.indexOf(prevValue), 1 );
alreadyUsed.push(newValue);
$(this).data("previous",newValue);
}else{
alert("Field is already in use.\nPlease, select a different field.");
$(this).val(prevValue);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<select name="dd1">
<option value="0">-Select-</option>
<option value="cat">cat</option>
<option value="dog">dog</option>
<option value="bear">bear</option>
</select>
<br />
<br />
<select name="dd2">
<option value="0">-Select-</option>
<option value="cat">cat</option>
<option value="dog">dog</option>
<option value="bear">bear</option>
</select>
<br />
<br />
<select name="dd3">
<option value="0">-Select-</option>
<option value="cat">cat</option>
<option value="dog">dog</option>
<option value="bear">bear</option>
</select>
<br />
<br />
</div>
You code is a bit more complicated, and obviously does other things, but perhaps this simple working version will help.
I need to alert if you haven't selected anything and couldn't get it to work. It needs to show what is where wrong and alert with a window.
<!DOCTYPE html>
<html>
<head>
<select id="ddlView">
<option value="0">Select</option>
<option value="1">test1</option>
<option value="2">test2</option>
<option value="3">test3</option>
</select>
<input type="button" onclick="myFunction()" value="select" />
<script>
function Validate()
{
var e = document.getElementById("ddlView");
var strUser = e.options[e.selectedIndex].value;
var strUser1 = e.options[e.selectedIndex].text;
if(strUser==0)
{
alert("Please select a user");
}
}
</td></head>
</html>
I think you have multiple problems here.
You need to add a body tag
Set the correct function name in your button.
you need a closing script tag
Give this a try:
<!DOCTYPE html>
<html>
<body>
<select id="ddlView">
<option value="0">Select</option>
<option value="1">test1</option>
<option value="2">test2</option>
<option value="3">test3</option>
</select>
<input type="button" onclick="Validate()" value="select" />
<script type="text/javascript">
function Validate()
{
var e = document.getElementById("ddlView");
var strUser = e.options[e.selectedIndex].value;
var strUser1 = e.options[e.selectedIndex].text;
if(strUser==0)
{
alert("Please select a user");
}
}
</script>
</body>
</html>
This is not you asked for but you can still consider what i did.
Have an option with value 0 which is going to be the default option of the dropdown and add required attribute to the select element.
Once this select element is in a form and is submitted ,HTML is automatically going to take over the validation part.
<select required>
<option value="">Select</option>
<option value="1">Option1</option>
</select>
<body>
<div>
<span>Select the course : </span>
<select id="ddlView">
<option value="0">Select</option>
<option value="1">Java Script</option>
<option value="2">CSS</option>
<option value="3">JQuery</option>
<option value="3">HTML</option>
<option value="3">C#</option>
</select>
</div>
<br >
<input type="button" class="btn" value="Submit" id="btnSubmit" onclick="ddlValidate();" />
<script type="text/javascript">
function ddlValidate() {
var e = document.getElementById("ddlView");
var optionSelIndex = e.options[e.selectedIndex].value;
var optionSelectedText = e.options[e.selectedIndex].text;
if (optionSelIndex == 0) {
alert("Please select a Course");
}
else {
alert("Success !! You have selected Course : " + optionSelectedText); ;
}
}
</script>
That has to be in your form processing script, you can just add it to the top of your code and check if it has been submitted.
// Place this atop of your script.
if(isset($_POST)) {
if($_POST['member_id']) {
// Your codes here
}
}
call this function at a button click(OnClientClick=" return Validate()") you have to list an item for the 0'th positions(ddlView.Items.Insert(0, new ListItem("Select...", "0"));)
function Validate(){
var region = document.getElementById('<%=ddlView.ClientID%>').value;
if (region == 0) {
alert("Please select a user");
return false;
}
}