Hey guys I am using JavaScript to select a specific value(option) from the html select form tag, but whenever I call my JavaScript function I get a single message repeating for all the choices I want to select.
Ex: If I choose to select 'Rabbit' from the list of options and then display a message saying 'Rabbit chosen'; the message will display for each option/value selected.
Here is my JavaScript Code:
var element = document.getElementById('choices').value;
function SelectElement() {
if (element = 'Rabbit') {
alert("Rabbit Selected");
}
else if (element = 'Wall') {
alert("Wall Selected");
}
else if (element = 'Arrow') {
alert("Arrow Selected");
}
}
Here is my html code:
<form>
<select id="choices" >
<option>Rabbit</option>
<option>Wall</option>
<option>Arrow</option>
</select>
<input type="button" value="Submit" onclick="SelectElement()"/>
</form>
Can you smart guys please help me????
A. You should fetch the value each time before calling the function and then check it otherwise your element variable won't refresh at all.
B. To compare two values you should use ==, = is an assignment operator.
function SelectElement() {
var element = document.getElementById('choices').value;
if (element == 'Rabbit') {
alert("Rabbit Selected");
}
}
(As your question is not much clear) if you just want to alert the selected value for every option clicked, just do:
function SelectElement() {
var element = document.getElementById('choices').value;
alert(element+" Selected");
}
This is basic string concatenation.
There is a something called selected == true or false in a "select" tag.
You could write in HTML :
<form>
<select id="choices">
<option id="Rabbit">Rabbit</option>
<option id="Wall">Wall</option>
<option id="Arrow">Arrow</option>
</select>
</form>
<button onclick="TakeElement()">Click</button>
You could write in javascript:
var ra = document.getElementById('Rabbit');
var wa = document.getElementById('Wall');
var ar = document.getElementById('Arrow');
function TakeElement() {
if (ra.selected == true) {
alert("Rabbit is selected");
}
if (wa.selected == true) {
alert("Wall is selected");
}
if (ar.selected == true) {
alert("Arrow is selected");
}
}
I think you must replace element ='rabbit' with element =='rabbit'
== is comparison operator
and = is assignment operator
Related
I have a HTML form having select box. On selection of first drop down, next drop down should be auto filled using AJAX.
On Download Records (id="getCsv") button click event a CSV file is generated. Problem is, I want to make all the fields mandatory. Here is the jquery code
var teacher_name = $("#sel_teacher option:selected").text();
var unittest_name = $("#sel_test1 option:selected").text();
var class_name = $("#sel_class1 option:selected").text();
var class_id = $('#sel_class1').val();
var division_name = $("#sel_div1 option:selected").text();
var division_id = $('#sel_div1').val();
var subject_name = $("#sel_sub1 option:selected").text();
if (teacher_name == "") {
alert('Please Select Teacher Name.');
return false;
} else if(class_name == "") {
alert('Please Select Class Name.');
return false;
} else if(division_name == "") {
alert('Please Select Division Name.');
return false;
} else if(subject_name == "") {
alert('Please Select Subject Name.');
return false;
} else if(unittest_name == "") {
alert('Please Select Unit Test Name.');
return false;
} else {
var myObject = new Object();
myObject.class_name = class_name;
myObject.class_id = class_id;
myObject.division_name = division_name;
myObject.division_id = division_id;
myObject.subject_name = subject_name;
myObject.test_name = unittest_name;
var formData = JSON.stringify(myObject);
$('#getCsv').attr('href','csv_generator.php?data=' + formData);
}
The problem is that when I click Download Records, even though the first select box is empty directly alert box for second select box pops up. I tried to solve this problem using the below, but no luck.
if ($("#sel_teacher").attr("selectedIndex") == 0) {
alert("You haven't selected anything!");
return false;
}
Can anybody please help me with this? Any help is appreciated.
selectedIndex is a property, use prop:
$("#sel_teacher").prop("selectedIndex")
Also, you can simplify your code by retrieving the selected value using just $("#sel_teacher").val() and compare to empty string (assuming the value of that option is empty).
var teacher_name = $("#sel_teacher").val();
// get other <select /> values here...
if (teacher_name == '') {
alert("You haven't selected anything!");
return false;
}
// test other values here...
It might be because of the default value that you have given for the first text-box.Just change the value to "" onclick or on blur on that text-box.
Or you can simply handle this matter via HTML5 attribute required and adding onchange() Event Listener .
<select name="sel_teacher" onchange="get_value();" id="sel_teacher" required>
<option>--Select Teacher Name--</option>
</select>
<script>
function get_value() {
var teacher_name = $("#sel_teacher").val();
// get other <select /> values here...
if (teacher_name == '') {
alert("You haven't selected anything!");
return false;
} else {
// write code when teacher_name is selected
}
}
</script>
I have a form with multiple checkboxes and I want to use JavaScript to make sure at least one is checked. This is what I have right now but no matter what is chosen an alert pops up.
JS (wrong)
function valthis(){
if (document.FC.c1.checked) {
alert ("thank you for checking a checkbox")
} else {
alert ("please check a checkbox")
}
}
HTML
<p>Please select at least one Checkbox</p>
<br>
<br>
<form name = "FC">
<input type = "checkbox" name = "c1" value = "c1"/> C1
<br>
<input type = "checkbox" name = "c1" value = "c2"/> C2
<br>
<input type = "checkbox" name = "c1" value = "c3"/> C3
<br>
<input type = "checkbox" name = "c1" value = "c4"/> C4
<br>
</form>
<br>
<br>
<input type = "button" value = "Edit and Report" onClick = "valthisform();">
So what I ended up doing in JS was this:
function valthisform(){
var chkd = document.FC.c1.checked || document.FC.c2.checked||document.FC.c3.checked|| document.FC.c4.checked
if (chkd == true){
} else {
alert ("please check a checkbox")
}
}
I decided to drop the "Thank you" part to fit in with the rest of the assignment. Thank you so much, every ones advice really helped out.
You should avoid having two checkboxes with the same name if you plan to reference them like document.FC.c1. If you have multiple checkboxes named c1 how will the browser know which you are referring to?
Here's a non-jQuery solution to check if any checkboxes on the page are checked.
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
var checkedOne = Array.prototype.slice.call(checkboxes).some(x => x.checked);
You need the Array.prototype.slice.call part to convert the NodeList returned by document.querySelectorAll into an array that you can call some on.
This should work:
function valthisform()
{
var checkboxs=document.getElementsByName("c1");
var okay=false;
for(var i=0,l=checkboxs.length;i<l;i++)
{
if(checkboxs[i].checked)
{
okay=true;
break;
}
}
if(okay)alert("Thank you for checking a checkbox");
else alert("Please check a checkbox");
}
If you have a question about the code, just comment.
I use l=checkboxs.length to improve the performance. See http://www.erichynds.com/javascript/javascript-loop-performance-caching-the-length-property-of-an-array/
I would opt for a more functional approach. Since ES6 we have been given such nice tools to solve our problems, so why not use them.
Let's begin with giving the checkboxes a class so we can round them up very nicely.
I prefer to use a class instead of input[type="checkbox"] because now the solution is more generic and can be used also when you have more groups of checkboxes in your document.
HTML
<input type="checkbox" class="checkbox" value=ck1 /> ck1<br />
<input type="checkbox" class="checkbox" value=ck2 /> ck2<br />
JavaScript
function atLeastOneCheckboxIsChecked(){
const checkboxes = Array.from(document.querySelectorAll(".checkbox"));
return checkboxes.reduce((acc, curr) => acc || curr.checked, false);
}
When called, the function will return false if no checkbox has been checked and true if one or both is.
It works as follows, the reducer function has two arguments, the accumulator (acc) and the current value (curr). For every iteration over the array, the reducer will return true if either the accumulator or the current value is true.
the return value of the previous iteration is the accumulator of the current iteration, therefore, if it ever is true, it will stay true until the end.
Check this.
You can't access form inputs via their name. Use document.getElements methods instead.
Vanilla JS:
var checkboxes = document.getElementsByClassName('activityCheckbox'); // puts all your checkboxes in a variable
function activitiesReset() {
var checkboxesChecked = function () { // if a checkbox is checked, function ends and returns true. If all checkboxes have been iterated through (which means they are all unchecked), returns false.
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
return true;
}
}
return false;
}
error[2].style.display = 'none'; // an array item specific to my project - it's a red label which says 'Please check a checkbox!'. Here its display is set to none, so the initial non-error label is visible instead.
if (submitCounter > 0 && checkboxesChecked() === false) { // if a form submit has been attempted, and if all checkboxes are unchecked
error[2].style.display = 'block'; // red error label is now visible.
}
}
for (var i=0; i<checkboxes.length; i++) { // whenever a checkbox is checked or unchecked, activitiesReset runs.
checkboxes[i].addEventListener('change', activitiesReset);
}
Explanation:
Once a form submit has been attempted, this will update your checkbox section's label to notify the user to check a checkbox if he/she hasn't yet. If no checkboxes are checked, a hidden 'error' label is revealed prompting the user to 'Please check a checkbox!'. If the user checks at least one checkbox, the red label is instantaneously hidden again, revealing the original label. If the user again un-checks all checkboxes, the red label returns in real-time. This is made possible by JavaScript's onchange event (written as .addEventListener('change', function(){});
You can check that atleast one checkbox is checked or not using this simple code. You can also drop your message.
Reference Link
<label class="control-label col-sm-4">Check Box 2</label>
<input type="checkbox" name="checkbox2" id="checkbox2" value=ck1 /> ck1<br />
<input type="checkbox" name="checkbox2" id="checkbox2" value=ck2 /> ck2<br />
<script>
function checkFormData() {
if (!$('input[name=checkbox2]:checked').length > 0) {
document.getElementById("errMessage").innerHTML = "Check Box 2 can not be null";
return false;
}
alert("Success");
return true;
}
</script>
< script type = "text/javascript" src = "js/jquery-1.6.4.min.js" > < / script >
< script type = "text/javascript" >
function checkSelectedAtleastOne(clsName) {
if (selectedValue == "select")
return false;
var i = 0;
$("." + clsName).each(function () {
if ($(this).is(':checked')) {
i = 1;
}
});
if (i == 0) {
alert("Please select atleast one users");
return false;
} else if (i == 1) {
return true;
}
return true;
}
$(document).ready(function () {
$('#chkSearchAll').click(function () {
var checked = $(this).is(':checked');
$('.clsChkSearch').each(function () {
var checkBox = $(this);
if (checked) {
checkBox.prop('checked', true);
} else {
checkBox.prop('checked', false);
}
});
});
//for select and deselect 'select all' check box when clicking individual check boxes
$(".clsChkSearch").click(function () {
var i = 0;
$(".clsChkSearch").each(function () {
if ($(this).is(':checked')) {}
else {
i = 1; //unchecked
}
});
if (i == 0) {
$("#chkSearchAll").attr("checked", true)
} else if (i == 1) {
$("#chkSearchAll").attr("checked", false)
}
});
});
< / script >
Prevent user from deselecting last checked checkbox.
jQuery (original answer).
$('input[type="checkbox"][name="chkBx"]').on('change',function(){
var getArrVal = $('input[type="checkbox"][name="chkBx"]:checked').map(function(){
return this.value;
}).toArray();
if(getArrVal.length){
//execute the code
$('#msg').html(getArrVal.toString());
} else {
$(this).prop("checked",true);
$('#msg').html("At least one value must be checked!");
return false;
}
});
UPDATED ANSWER 2019-05-31
Plain JS
let i,
el = document.querySelectorAll('input[type="checkbox"][name="chkBx"]'),
msg = document.getElementById('msg'),
onChange = function(ev){
ev.preventDefault();
let _this = this,
arrVal = Array.prototype.slice.call(
document.querySelectorAll('input[type="checkbox"][name="chkBx"]:checked'))
.map(function(cur){return cur.value});
if(arrVal.length){
msg.innerHTML = JSON.stringify(arrVal);
} else {
_this.checked=true;
msg.innerHTML = "At least one value must be checked!";
}
};
for(i=el.length;i--;){el[i].addEventListener('change',onChange,false);}
<label><input type="checkbox" name="chkBx" value="value1" checked> Value1</label>
<label><input type="checkbox" name="chkBx" value="value2"> Value2</label>
<label><input type="checkbox" name="chkBx" value="value3"> Value3</label>
<div id="msg"></div>
$('input:checkbox[type=checkbox]').on('change',function(){
if($('input:checkbox[type=checkbox]').is(":checked") == true){
$('.removedisable').removeClass('disabled');
}else{
$('.removedisable').addClass('disabled');
});
if(($("#checkboxid1").is(":checked")) || ($("#checkboxid2").is(":checked"))
|| ($("#checkboxid3").is(":checked"))) {
//Your Code here
}
You can use this code to verify that checkbox is checked at least one.
Thanks!!
I have one select box and one text box are there. I need to the validation like if both are selected I need alert like "Either select a name or pick the name", If I did not select both i need alert like "Please select a name or pick the name", If I select one of them I need alert like "Thank you for selecting the name". I did it by java script but I did not get the result. Can it be done by using java script / Jquery? Any suggestions
<body>
pick name:
<select id="ddlView">
<option value="0">Select</option>
<option value="1">test1</option>
<option value="2">test2</option>
<option value="3">test3</option>
</select>
</br>
select name:
<input type= "text" name="raju" id="raju"></input>
<input type="button" onclick="Validate()" value="select" />
<script type="text/javascript">
function Validate()
{
var name = document.getElementById("raju");
var e = document.getElementById("ddlView");
var strUser = e.options[e.selectedIndex].value;
var strUser1 = e.options[e.selectedIndex].text;
if(strUser==0 && (name==null || name== ' '))
{
alert("Please select a name or pick the name");
}
else if( (!(strUser==0)) &&(! (name==null || name== ' ')))
{
alert("Either select a name or pick the name");
}
else
{
alert("Thank you for selecting the name");
}
}
</script>
</body>
Here is your same validation using JQuery as you also mentioned:
function Validate()
{
var name = $("#raju").val();
var selected_name = $('#ddlView :selected').val();
if(selected_name == 0 && name == "")
{
alert("Please select a name or pick the name");
}
else if( !(selected_name == 0) && name != "")
{
alert("Either select a name or pick the name");
}
else
{
alert("Thank you for selecting the name");
}
}
Fiddle
Your problem is that you get the input, not the value.
Replace var name = document.getElementById("raju"); with var name = document.getElementById("raju").value;
Also, you compare the name with null and blank space. You must compare it with empty string. (name == '')
When you saw on my Jsfiddle code, I don't use oonclick attribute but a event listener on javascript (realy better for your html)..
document.getElementById("myBtn").onclick= function ()
One second poitn you have forget tu retrieve .value of you name input (so already return [HTML DOM object] and not null or a value.
var name = document.getElementById("raju").value;
Since your post was in pure JavaScript, I've decided to answer accordingly. As mentioned, you shouldn't check an empty string for " " but rather '' or "". Furthermore, you shouldn't even need to do that, since you can simply check if (str) { // string exists }. For your name variable, you're referring to an HTML element and not it's string value. So, all in all (a few errors), nothing majorly wrong here.
I've abstracted this process a tiny bit to give you an idea of how to validate many similar fields without a whole lot of repetitive code.
Note: You should find a way to replace your inline event handlers with unobtrusive handlers. Example:
document.getElementById('someButton').onclick = Validate;
That being said, here's a few suggestions:
var emptyString = function(str) {
if (str) {
return false;
}
return true;
};
var emptySelect = function(sel) {
if (parseInt(sel) !== 0) {
return false;
}
return true;
};
function Validate() {
var name = document.getElementById("raju").value;
var e = document.getElementById("ddlView");
var strUser = e.options[e.selectedIndex].value;
switch (true) {
case (!emptySelect(strUser) && !emptyString(name)):
alert('Either select a name or pick a name.');
break;
case (emptySelect(strUser) && emptyString(name)):
alert('Please select a name or pick a name.');
break;
default:
// Possibly some default validation
alert('Thanks for picking a name');
break;
}
}
I have a dropdown list and a javascript function which disables other fields when a certain value from the dropdown list is selected.
Javascript Code
function maritalStatusChange()
{
var dropdown = document.getElementById("maritalstatus").value;
if(dropdown == 'Single')
{
document.getElementById("spousefld").disabled = true;
document.getElementById("spouse_occupation").disabled = true;
document.getElementById("address3").disabled = true;
document.getElementById("children_no").disabled = true;
document.getElementById("spousefld").value = "";
document.getElementById("spouse_occupation").value = "";
document.getElementById("address3").value = "";
document.getElementById("children_no").value= "None";
}
if(dropdown == 'Married')
{
document.getElementById("spousefld").disabled = false;
document.getElementById("spouse_occupation").disabled= false;
document.getElementById("address3").disabled = false;
document.getElementById("children_no").disabled = false;
document.getElementById("maritalstatus").value= 'Married';
}
if(dropdown == 'Separated')
{
document.getElementById("spousefld").disabled = false;
document.getElementById("spouse_occupation").disabled= false;
document.getElementById("address3").disabled = false;
document.getElementById("children_no").disabled = false;
}
if(dropdown == 'Widowed')
{
document.getElementById("spousefld").disabled = false;
document.getElementById("spouse_occupation").disabled= false;
document.getElementById("address3").disabled = false;
document.getElementById("children_no").disabled = false;
}
}
Here is the HTML code of the dropdown list and where I call the javascript function.
<select name="maritalstatus" id="maritalstatus" onchange="maritalStatusChange();">
<option>---------------</option>
<option value='Single'>Single</option>
<option value='Married'>Married</option>
<option value='Separated'>Separated</option>
<option value='Widowed'>Widowed</option>
</select><font color="red">*</font>
Right now, the only thing that works is when I select the "Single" option however, it does not seem to get proper selected value for the rest of the options. Can anyone tell me what I did wrong?
Thanks!
Try This:
var dropdown = document.getElementById("maritalstatus").options[document.getElementById("maritalstatus").selectedIndex].value;
You should try "selectedIndex":
document.getElementById("maritalstatus").selectedIndex;
The above code works fine. You can see it at: http://jsfiddle.net/WmHCs/
What is the actual error? Maybe some other part of the code?
Try Below code
var eve = document.getElementById("maritalstatus");
var data = eve.options[eve.selectedIndex].value;
You are using single quotas in HTML. Switch them to double quotas. All values for options are assigned with those single quotas. This is what you are actually comparing: ("'Single'"=="Single") => false.
EDIT
If this code is supposed to add the selection in your db, check if-blocks other than Single. In case Single you set some values, but other blocks are making some disablings only.
You just need to get value from element by id and then alert the value.
Create a function and call it on change. it works in many of values dynamically generated, no limitaion of entries in dropdown.
<select name="maritalstatus" id="maritalstatus" onchange="maritalStatusChange();">
function maritalStatusChange()
{
var getValue = document.getElementById("maritalstatus").value;
alert(getValue);
}
I have a form in HTML, that has several select elements, what is the best way to make validation for them in such way that no two select elements can have same value, validation function should fire on select, so it can check are there any selects with the same option value if yes then alert something, can I get a explanation how to write this in javascript?
Thank you
here is a bit of HTML code I want to validate :
<form name="forma" action="" method="POST">
<select name="sel1">
<option>Please select</option>
<option>brand1</option>
<option>brand2</option>
<option>brand3</option>
</select>
<select name="sel2">
<option>Please select</option>
<option>brand1</option>
<option>brand2</option>
<option>brand3</option>
</select>
<select name="sel3">
<option>Please select</option>
<option>brand1</option>
<option>brand2</option>
<option>brand3</option>
</select>
</form>
Here is the solution slightly adjusted but this is it:
var selectTest = function () {
var i, j;
sels = [document.getElementById("sel1"), document.getElementById("sel2"), document.getElementById("sel3")];
for (i = 0; i < sels.length; i += 1) {
for (j = i + 1; j < sels.length; j += 1) {
if(sels[i].value != "Please select")
{
if (sels[i].value === sels[j].value) {
alert("Selected values must be different");
return;
}
}
}
}
};
Special tnx to austin cheney, thanks to everyone who posted and participated.
First, don't use the name attribute as a reference point for script. Name refers to an array of named elements in the DOM, which is typically useless in the global DOM outside of form controls. When using the name array it is difficult to tell child nodes apart from child nodes of a same named element. Use the id attribute for use with script, which is a unique identifier instead.
var selTest = function () {
var i, j, error = document.getElementById("error"),
sels = [document.getElementById("sel1"), document.getElementById("sel2"), sel3 = document.getElementById("sel3")];
for (i = 0; i < sels.length; i += 1) {
for (j = i + 1; j < sels.length; j += 1) {
if (sels[i].value === sels[j].value) {
error.display = "block";
sels[i].backgroundColor = "#f00";
sels[j].backgroundColor = "#f00";
return false;
}
}
}
};
EDIT: changed return; to return false; for use with an onsubmit event.
Simply add the id attribute value of the select lists to the "sels" array in the code above. The above code will make a hidden element with an id of "error" appear if the test results in a true condition. It will also change the background color of the offended select lists to red.
I would generally recommend using jQuery for this as it simplifies it quite a bit. You'd want to do something along these lines.
function hasDuplicates() {
var dupe = false;
$("select option:selected").each(function(i) {
var id = $(this).parent().attr("id");
var value = $(this).attr("value");
$("select option:selected").each(function(c) {
if ($(this).parent().attr("id") != id && $(this).attr("value") == value) {
alert("Duplicate");
dupe = true;
return false;
}
});
if (dupe) {
return false;
}
});
return dupe;
}
This will cycle through all the select boxes on the page and compare each one to every other one. If there's a duplicate value it will popup an alert and return true.
For it to fire when a change to a select box is made you'd want to add onchange events to each as shown below. Each select will need a unique id to be set, although you could change the calls to attr("id") to attr("name") if you don't want to add ID's.
<select onchange="hasDuplicates()">...
Performance wise it may make sense to store the values in an array, as this solution hits the DOM quite a lot by having a nested loop.
Give onchange="validate('1')" onchange="validate('2')" onchange="validate('3')" for each selecte statement.
function validate(x){
if(x==1)
{
var selectedvalue=document.forma.sel1.options[document.forma.sel1.selectedIndex].value
if(selectedvalue==document.forma.sel2.options[document.forma.sel2.selectedIndex].value ||
selectedvalue==document.forma.sel3.options[document.forma.sel3.selectedIndex].value)
alert("No two values cannot be same");
}
esle if(x==2)
{
var selectedvalue=document.forma.sel2.options[document.forma.sel2.selectedIndex].value
if(selectedvalue==document.forma.sel1.options[document.forma.sel1.selectedIndex].value ||
selectedvalue==document.forma.sel3.options[document.forma.sel3.selectedIndex].value)
alert("No two values cannot be same");
}
else if(x==3)
{
var selectedvalue=document.forma.sel3.options[document.forma.sel3.selectedIndex].value
if(selectedvalue==document.forma.sel1.options[document.forma.sel1.selectedIndex].value ||
selectedvalue==document.forma.sel1.options[document.forma.sel1.selectedIndex].value)
alert("No two values cannot be same");
}
}