I have used the code (below) which was featured on jsfiddle. The problem i have is that if i change the option value to be different from the text value, it then adds the value back into the text field on change.
jQuery(function(){
jQuery('.selbox').change(function(){
var val = jQuery(this).val();
var sel = jQuery(this);
if(val != "")
{
if(sel.data("selected"))
{
var oldval = sel.data("selected");
sel
.siblings('select')
.append(jQuery('<option/>').attr("value", oldval).text(oldval));
}
sel
.data("selected", val)
.siblings('select')
.children('option[value=' + val + ']')
.remove();
}
else if(val == "")
{
if(sel.data("selected"))
{
var oldval = sel.data("selected");
sel
.removeData("selected")
.siblings('select')
.append(jQuery('<option/>').attr("value", oldval).text(oldval));
}
}
});
});
I am using code
<option value="1">text here</option>
Please see here for the original code http://jsfiddle.net/BUuZv/2/
Instead of removing them and adding them, you could simply hide/show them like this fiddle
$(function() {
$('.selbox').change(function() {
var val = $(this).val();
var sel = $(this);
if (val != "") {
if (sel.data("selected")) {
var oldval = sel.data("selected");
sel.siblings('select').find('option[value="' + oldval + '"]').show()
}
sel.data("selected", val).siblings('select').children('option[value=' + val + ']').hide();
}
else {
if (sel.data("selected")) {
var oldval = sel.data("selected");
sel.removeData("selected").siblings('select').find('option[value="' + oldval + '"]').show()
}
}
});
});
Was trying to work this out today, here is how I have done it. When the user selects other, it gives a prompt box to add the new option value.
function edit_other(e){ //e just stands for element, it can be any varaible name e is just standard practice after using "this"
if(e.value == "Other"){
//only run function if "other" option has been selected
var proceed = false;
while(proceed == false){
prompt_response = prompt("Please enter new material type:"); //Create Prompt box
if (typeof(prompt_response) == "string"){
prompt_response = prompt_response.trim(); //tidy end
if (prompt_response != ""){//// no value provided by the user on "ok button press"
proceed = true;
//alert('Please Enter a value to continue or press Cancle!');
}
}
if (prompt_response === null){////cancel hits
proceed = false; //make sure proceed is still false
break;
}
}
//once the user enters a valid value add option script
if(proceed == true){
var new_option = document.createElement("option"); //create nre DOM option element
new_option.text = prompt_response; //Make the text value equal to promt repsonse
new_option.value = prompt_response; //Make the option select value equal to promt repsonse
new_option.selected = true; //OPTIONAL: select the new added value, most people will select this if they are adding a new value
e.add(new_option); //add new option
}
}
}
<select id="xxx" onchange="edit_other(this)">
<option value="1"> First Option </option>
<option value="Other">Other</option>
<select>
Related
My page have multiple textboxes i wanted to make sure if user select value from text box 1 and leaves text box 2 empty then it should alert a popup that you must have to enter values in both textboxes.
i do not want to compare values with each other.(Like both textbox value must be same)
Textbox 1 is Number field and text box 2 is date field.
If any one value is entered then it should not allow user to submit page it should stop processing and redirect to that textbox which is empty.
Now what i have tried so far.
$( "#button_id" ).click(function() {
var n = document.getElementById('text1');
var m = document.getElementById('text2');
if(n.value.trim() != "" || n.value == undefined)
{
if (n.value.trim() != "" && m.value.trim() == "")
{
alert("text1 should have some value");
return false;
}
}
if(m.value.trim() != "" || m.value == undefined)
{
if (m.value.trim() != "" && n.value.trim() == "")
{
alert("text2 should have some values");
return false;
}
}
});
As mention below code i just wanted to check if textbox is disable or not if textbox is disable then do not test for validation else do.
Partial Solution :
var _domArray = [$("#textbox1"),$("#textbox2")]
var chk = $x('textbox2').disabled = false;
$( "buttonid" ).click(function() {
_domArray.forEach(function(item){
if(item.val() ==''){
var _getId =item.attr('id');
alert(_getId +" should have some value" );
this.browserEvent.preventDefault();
this.browserEvent.stopImmediatePropagation();
return false;
}
})
});
Use the required attribute on your <input>s, then you can check in JavaScript with document.querySelector('form.insertSelectorHere').matches(':valid').
Use an array to store the DOM element,Loop through it and check to check if it is empty, If so through an alert.
Also assuming you are using input type number & date
var _domArray = [$("#text1"),$("#text2")]
$( "#button_id" ).click(function() {
_domArray.forEach(function(item){
if(item.val() ==''){
var _getId =item.attr('id');
alert(_getId +" should have some value" )
}
})
});
Using jquery since you have tagged this with jquery
jsfiddle
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 default array that have some fixed values from which i am showing a multiselect dropdown to user.So on focusout of the drop down i want to check that whether the values are selected have the all those values that are in the default array.If the values are missing i want to alert them to the user
HTML
<form action="#" method="post">
<fieldset>
<label for="selectedItemLists">Select values:</label>
<select id="selectedItemLists" name="selectedItemLists" multiple>
<option val="value1" selected >value1</option>
<option val="value2">value2</option>
<option val="value3" selected>value3</option>
<option val="value4">value4</option>
<option val="value5">value5</option>
</select>
</fieldset>
<fieldset>
<input type="submit" value="submit" />
</fieldset>
</form>
jQuery
var default_values = ["value1","value3"];
$("#selectedItemLists").live('focusout',function(){
var new_selectedvalues = $("#selectedItemLists").val();
//here i want to compare both the arrays and alert him that default values are missing
});
A simple nested $.each loop will do it:
Demo
//here i want to compare both the arrays and alert him that default values are missing
$.each(default_values, function(_, defaultVal){
var found = false;
$.each(new_selectedvalues, function(){
if(this == defaultVal){
found = true;
return false;
}
});
if(!found){
alert("Please select the default: " + defaultVal);
}
});
Note: .live() is deprecated from jQuery 1.7, so .on should be used instead (unless you are working with the old version).
Just try with:
var default_values = ["value1","value3"];
$("#selectedItemLists").on('blur',function(){
var values = $(this).val();
if ($(values).not(default_values).length == 0 && $(default_values).not(values).length == 0) {
console.log('equal');
} else {
console.log('not equal');
}
});
http://jsfiddle.net/f5BbT/
try something like this
var default_values = ["value1","value3"];
$("#selectedItemLists").focusout(function() {
var selected_val = $('#selectedItemLists').val();
if(selected_val.length < default_values.length){
alert('value not present');
}else{
var flag = true;
for(var i= 0;i<default_values.length;i++){
if(selected_val.indexOf(default_values[i]) == -1){
flag = false;
}
}
if(!flag){
alert('value not present');
}else{
alert('value present');
}
}
});
I would do someting like this:
var default_values = ["value1","value3"];
var displayValues = [];
$("#selectedItemLists").on('blur',function(){
$.each(default_values, function(index, value) {
if($.inArray(value, $("#selectedItemLists").val()) === -1)
{
displayValues.push(value);
}
});
});
alert(displayValues);
please use
$("#selectedItemLists").on('blur',function(){
instead of
$("#selectedItemLists").live('focusout',function(){
live is deprecated since jQuery 1.7 and removed in 1.9
try this JSFIDDLE
var default_values = ["value1", "value3"];
$("#selectedItemLists").on('blur', function () {
var missing_values = [];;
var values = $(this).val();
//******************************************
//checking missing values in default_values
//******************************************
$.each(values, function (key, value) {
if ($.inArray(value, default_values) == -1) {
missing_values.push(value);
}
});
alert(missing_values);
// alerts missing selected values in default_values
});
or try
var default_values = ["value1", "value3"];
$("#selectedItemLists").on('blur', function () {
var missing_values = [];
var values = $(this).val();
//******************************************
//checking default values in selection
//******************************************
$.each(default_values, function (key, value) {
if ($.inArray(value, values) == -1) {
missing_values.push(value);
}
});
alert(missing_values);
// alerts missing default values in selected
});
I have drop-down and Textbox inside a Gridview so I want to check the followings on a button click:
(1) Check if NOTHING is selected from the drop down first (the drop-down options are either YES, NO or NA) . If nothing is selected, I want to show message that reads like this “Please make selection from the drop-down”
(2) If the selection from the drop-down is NO and the Textbox is blank or empty then I want to show message that says: “Please provide comments”
The first code checks if the text-box is blank and it works and the 2nd code checks if no selection is made from the drop down and that one works fine too so how can i combine between those 2 codes? I want to execute both codes on button click, right now it is only calling the first code. please help. Thanks.
here is my code that checks if the textbox is blank:
<script type ="text/javascript">
function Validate() {
var flag = false;
var gridView = document.getElementById('<%= GridView1.ClientID %>');
for (var i = 1; i < gridView.rows.length; i++) {
var selects = gridView.rows[i].getElementsByTagName('select');
var areas = gridView.rows[i].getElementsByTagName('textarea');
if (selects != null && areas != null) {
if (areas[0].type == "textarea") {
var txtval = areas[0].value;
var selectval = selects[0].value;
if (selectval == "No" && (txtval == "" || txtval == null)) {
flag = false;
break;
}
else {
flag = true;
document.getElementById('<%=btnSubmit.ClientID%>').style.visibility = 'visible';
}
}
}
}
if (!flag) {
alert('Please note that comments are required if you select "No" from the dropdown box. Thanks');
document.getElementById('<%=btnSubmit.ClientID%>').style.visibility = 'hidden';
}
return flag;
}
</script>
and here is the code that checks the drop-down
<script type="text/javascript">
function validate_DD() {
var flag = true;
var dropdowns = new Array(); //Create array to hold all the dropdown lists.
var gridview = document.getElementById('<%=GridView1.ClientID%>'); //GridView1 is the id of ur gridview.
dropdowns = gridview.getElementsByTagName('Select'); //Get all dropdown lists contained in GridView1.
for (var i = 0; i < dropdowns.length; i++) {
if (dropdowns.item(i).value == 'Select') //If dropdown has no selected value
{
flag = false;
break; //break the loop as there is no need to check further.
}
}
if (!flag) {
alert('Please select either Yes, No or NA in each dropdown and click the Save button again. Thanks');
document.getElementById('<%=btnSubmit.ClientID%>').style.visibility = 'hidden';
}
return flag;
}
</script>
Try this:
<select id="ddlCars">
<option value="1">Honda</option>
<option value="2" selected="selected">Toyota</option>
<option value="3">BMW</option>
</select>
Accessing dropdown:
To get the value:
var el = document.getElementById("ddlCars");
var val = el.options[el.selectedIndex].value; // val will be 2
To get the text:
var el = document.getElementById("ddlCars");
var car = el.options[el.selectedIndex].text; //car will be Toyota
I have 5 selection boxes and I want to get all option selected values into a variable like this: val+val+val+val
Below you can see my code, but it's not full working because if I have nothing selected I get +++++
if($('select').attr("selectedIndex") == 0) {
var allVariables = $("select option:selected").map(function(){
return this.value
}).get().join("+");
}
What am I missing?
It was returning empty values because your select option headers still represent a user selection, they just have no value. So add in a check for a value before you return it:
$('.find').click(function(e){
var Scat = $('#Scat option:selected').val();
var allVariables = $("select option:selected").map(function(){
if(this.value!=""){ //only return if we have a value
return this.value;
}
}).get().join('+');
alert(allVariables);
if(Scat == ""){
alert("Choose a Category");
} else {
// do something else
};
});