So I've got a standard select dropdown. One of the options in the select(the last one) I've got as a text string- var abc.
<select id="exampleselect">
<option>123</option>
<option>xyz</option>
<option>ABC</option>
</select>
var abc = "ABC";
What I'm trying to do is search through the select, find a match against var abc then change the match of var abc to being the selected option.
What I've tried:
//gets all the options from the select
var selectoptions = $('#exampleselect').find('option').text();
//if there is a match of var abc to any of the options in the select
if (selectoptions == abc)
{
//work out how to get the index/eq of the matched element
//put matched element as selected value
$('#exampleselect').val(matchedelementindex);
}
Live example.
As you don't use the value attribute, you can use this code:
var myVar = 'xyz';
$('#exampleselect option').each(function(e) {
var $this = $(this);
if ($this.text() === myVar) {
$this.prop('selected', true);
return false; // stops the iteration
}
});
You could also do it in one line by using the :contains() selector. But this would may not work if you have an option with text "ABC" and another with "ABCD":
$('#exampleselect option:contains('+myVar+')').prop('selected', true);
Although, I would recommend that you add a value attribute to your option elements:
<select id="exampleselect">
<option value="123">123</option>
<option value="xyz">xyz</option>
<option value="ABC">ABC</option>
</select>
this way you can do:
$('#exampleselect').val(myVar);
Try this:
var abc = "ABC";
$("#exampleselect option").each(function() {
if ($(this).text() == abc) {
$(this).attr("selected", true);
return false; // exit each loop
}
})
Or this, although this is slightly less readable:
var abc = "ABC";
$("#exampleselect option").each(function() {
$(this).attr("selected", $(this).text() == abc);
})
This fiddle may help you .
You can achieve this by CSS Selectors which are supported by jQuery
var searched="abc";
$('select option['+searched+']').attr("selected","selected");
http://jsfiddle.net/7EzqU/
// iterate all select options using jquery .each method
$('#exampleselect option').each(function () {
// check if current option text is equal to 'ABC'
if ($(this).text() == 'ABC') {
// get index of option
var index = $('#exampleselect').index($(this))
// set selectedIndex property to change to this option
$('#exampleselect').prop('selectedIndex', index);
}
})
this should do the trick:
http://jsfiddle.net/xXEVw/
Related
I have a HTML select list, which can have multiple selects:
<select id="mySelect" name="myList" multiple="multiple" size="3">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option> `
<option value="4">Fourth</option>
...
</select>
I want to get an option's text everytime i choose it. I use jQuery to do this:
$('#mySelect').change(function() {
alert($('#mySelect option:selected').text());
});
Looks simple enough, however if select list has already some selected options - it will return their text too. As example, if i had already selected the "Second" option, after choosing "Fourth" one, alert would bring me this - "SecondFourth". So is there any short, simple way with jQuery to get only the "current" selected option's text or do i have to play with strings and filter new text?
You could do something like this, keeping the old value array and checking which new one isn't in there, like this:
var val;
$('#mySelect').change(function() {
var newVal = $(this).val();
for(var i=0; i<newVal.length; i++) {
if($.inArray(newVal[i], val) == -1)
alert($(this).find('option[value="' + newVal[i] + '"]').text());
}
val = newVal;
});
Give it a try here, When you call .val() on a <select multiple> it returns an array of the values of its selected <option> elements. We're simply storing that, and when the selection changes, looping through the new values, if the new value was in the old value array ($.inArray(val, arr) == -1 if not found) then that's the new value. After that we're just using an attribute-equals selector to grab the element and get its .text().
If the value="" may contains quotes or other special characters that would interfere with the selector, use .filter() instead, like this:
$(this).children().filter(function() {
return this.value == newVal[i];
}).text());
Set a onClick on the option instead of the select:
$('#mySelect option').click(function() {
if ($(this).attr('selected')) {
alert($(this).val());
}
});
var val = ''
$('#mySelect').change(function() {
newVal = $('#mySelect option:selected').text();
val += newVal;
alert(val); # you need this.
val = newVal;
});
or let's play some more
val = '';
$('#id_timezone')
.focus(
function(){
val = $('#id_timezone option:selected').text();
})
.change(
function(){
alert(val+$('#id_timezone option:selected').text())
});
Cheers.
I have 3 columns of HTML selection fields which need to load otions dependent on the previous selection fields.
Selection in column 2 values will be dependant on selected value in column 1 selection. I have this raw JavaScript below which add 2 selection options to a an HTML select filed and then removes 2 based on the select value in selection 1.
My problem is that the part that removes the 2 selection field options is not removing both options but instead removes 1 of them.
Demo: http://jsfiddle.net/jasondavis/croh2nj8/3/
I realize some of this uses jQuery but the goal is to use raw JS without jQuery for this part in question....
$(document).ready(function() {
$("#action").change(function() {
var el = $(this) ;
var selectAttributeEl = document.getElementById('action-attribute');
if(el.val() === "form" ) {
var option = document.createElement('option');
option.text = 'Name';
var option2 = document.createElement('option');
option2.text = 'ActionURL';
selectAttributeEl.add(option);
selectAttributeEl.add(option2);
}else if(el.val() === "link" ) {
for (var i=0; i<selectAttributeEl.length; i++){
if (selectAttributeEl.options[i].value == 'Name'){
selectAttributeEl.remove(i);
}else if(selectAttributeEl.options[i].value == 'ActionURL'){
selectAttributeEl.remove(i);
}
}
}
});
});
The problem is in the for loop where you loop through the selectobject.options. When the first if condition is true, you mutate selectobject.options by removing the Name option. On the next iteration of the loop selectobject.options[i] now returns undefined.
Let's walk through the for loop to demonstrate:
i is 0, corresponding to option ID, nothing happens.
i is 1, corresponding to option Class, nothing happens.
i is 2, corresponding to option Name, the if statement is valid and it removes the Name option. Now selectobject.options has length of 3.
i is 3, which corresponds to undefined. That is, selectobject.options[3] is undefined since the previous iteration of the loop removed an item from selectobject.options.
One possible solution, in the if and else statements you could reset i back one, with i--. Here's an updated jsFiddle. Another option is too loop through selectobject.options backwards, as mutating the latter items won't effect the counter as it moves to the former items.
There are other ways to correct this as well, like creating a new options array based on the values you want to keep in the options, then loading it the new options into the select.
As I stated, you're getting the issue, very simply, because the for loop is started from index 0 and working your way up. When you remove an element, you remove it from the NodeList of options. Easiest way I know of is to start from the end of the node list and work your way to node number 0.
$(document).ready(function() {
$("#action").change(function() {
var el = $(this);
if (el.val() === "form") {
//$("#action-attribute").append(' <option value="Name">Name</option>');
//$("#action-attribute").append(' <option value="ActionURL">ActionURL</option>');
var x = document.getElementById('action-attribute');
var option = document.createElement('option');
option.text = 'Name';
var option2 = document.createElement('option');
option2.text = 'ActionURL';
x.add(option);
x.add(option2);
} else if (el.val() === "link") {
//$("#action-attribute option:last-child").remove() ;
var selectobject = document.getElementById("action-attribute");
var remove_array = ['Name', 'ActionURL'];
for (var i = selectobject.options.length - 1; i >= 0; i--) {
if (remove_array.indexOf(selectobject.options[i].value) != -1) {
selectobject.removeChild(selectobject.options[i]);
}
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
When :
<select id="action" name="action">
<option value="link">Link Clicked</option>
<option value="form">Form Submitted</option>
</select>
with:
<select id="action-attribute" name="action-attribute">
<option>ID</option>
<option>Class</option>
</select>
May I propose a different approach? Instead of maintaining the state of the menu by removing elements that shouldn't be there, blow away the menu option tags entirely and replace.
$(document).ready(function() {
var options = {
link: ['ID', 'Class']
},
dependentMenu = document.getElementById('action-attribute');
options.form = options.link.concat(['Name', 'ActionURL']);
$("#action").change(function() {
var el = $(this);
while (dependentMenu.firstChild) {
dependentMenu.removeChild(dependentMenu.firstChild);
}
options[el.val()].forEach(function(value) {
var option = document.createElement('option');
option.text = value;
dependentMenu.add(option);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
When :
<select id="action" name="action">
<option value="link">Link Clicked</option>
<option value="form">Form Submitted</option>
</select>
with:
<select id="action-attribute" name="action-attribute">
<option>ID</option>
<option>Class</option>
</select>
This my problem's semplification. I want to append some text after an input field (on update of the same field), only when the value of a select element is IT.
That's the fields:
<select id="billing_country">
<option value="FR">FR</option>
<option value="IT">IT</option>
</select>
<input type="text" id="woocommerce_cf_piva">
this is the script:
jQuery(document).ready(function () {
var $country_select = jQuery('#billing_country');
// When country change
$country_select.change(function () {
var $country = jQuery('#billing_country option:selected');
$country.each(function() {
FieldCheck(jQuery(this).val());
})
});
function FieldCheck($country) {
var $element = jQuery('#woocommerce_cf_piva');
if ($country == 'IT') {
$element.change(function () {
$element.after($country);
});
}
}
});
You can see this also on jsFiddle
Why it append country name also if i select FR?
It's difficult to understand what you're trying to do with your code.
You want the text input to change its value only if the select box has "IT" selected?
Why are you setting a change handler on the text input?
Why iterate through a select box's options if it's a single select? Just set the text input with the selected option's value, e.g.,
$(function() {
var $billingCountry = $('#billing_country');
$billingCountry.change(function() {
var $country = $('#billing_country option:selected');
fieldCheck($country.val());
});
function fieldCheck(country) {
var $element = $('#woocommerce_cf_piva');
if ($country !== 'IT') {
return;
}
$element.val(country);
}
});
https://jsfiddle.net/davelnewton/w5deffvk/
Edits
Naming conventions changed to reflect typical JS
Non-constructor function names start with lower-case
Non-JQ element vars don't get a leading $
Country value used as guard clause rather than nesting logic
This code is trivial, but nesting can make things harder to reason about
I would add a span and put the text in there so on subsequent change you can fix it:
<select id="billing_country">
<option value="FR">FR</option>
<option value="IT">IT</option>
</select>
<input type="text" id="woocommerce_cf_piva" /><span id="afterit"></span>
Note that this is still pretty verbose:
jQuery(document).ready(function() {
var $country_select = jQuery('#billing_country');
var $element = jQuery('#woocommerce_cf_piva');
// When country change
$country_select.on('change', function() {
var $country = jQuery(this).find('option:selected')[0].value;
var d = ($country == 'IT') ? $country : "";
$element.data('selectedcountry', d);
});
$element.on('change', function() {
var ct = $(this).data('selectedcountry');
//as you have it: $(this).after(ct);// append
// put it in the span to remove/blank out on subsequent changes
$('#afterit').text(ct);
});
});
Here is the total less-verbose version:
$('#woocommerce_cf_piva').on('change', function() {
var v = $('#billing_country').find('option:selected')[0].value;
$('#afterit').text((v == 'IT') ? v : "");
});
You have two problems:
input tag does not have onchange event; you should use onkeydown instead;
you should assign events before if conditions.
If I understand the problem correctly, you want to update input field with the value entered only when drop down selection is "IT". If that is the case, you need to watch input field event and invoke FieldCheck function from with in input field events.
So I have the following piece of HTML:
<select id="sel">
<option value="0">Option1</option>
<option value="1">Option2</option>
<option value="2">Option3</option>
<option value="3">Option4</option>
</select>
How do I check to see if #sel has an option based on the text value? ("Option1")
Try the following:
var opt = 'Option1';
if ($('#sel option:contains('+ opt +')').length) {
alert('This option exists')
}
Demo
edit: The above snippet uses the jQuery contains selector which filters elements that their textContent contains the specified value. For an exact match you can use the code snippet suggested in christian-mann's answer.
How to do this with Javascript (not jquery) – Jerry
var optionExists = [].some.call(document.getElementById('sel').options, function(option) {
return option.textContent === 'value';
});
The jQuery filter function accepts a function as its argument:
$('#sel option').filter(function() {
return $(this).text() === "Option1";
});
var length = $('#sel option').filter(function() {
return $(this).text() === "Option1";
}).length;
if(length == 0)
console.log('This option text doesn't exist.');
else
console.log('This option text exists ' + length + ' times.');
If length is 0, it doesn't exist. I typically don't like using contains, because it's not an exact match.
var hasOption1=$("option:contains('Option1')", "#sel").length==1; //true or false
I want to add 'change' events to 4 select boxes. I have done it using bind().
But I want to call different functions on change of each select box.
Say function1() on change event of SelectBox1...
How should I do it?
I am new to javascript & jquery, so please help.
Thank you
Suppose your HTML like this:
HTML
<select id="selectBox1">
</select>
<select id="selectBox2">
</select>
<select id="selectBox3">
</select>
<select id="selectBox4">
</select>
jQuery
$('select[id^=selectBox]').on('change', function() {
// to get the id of current selectBox
var selectId = this.id;
if(selectId == 'selectBox1') {
function1();
} else if(selecId == 'selectBox2') {
function2();
}
// and so on
});
Some more
$('select[id^=selectBox]').on('change', function() {
// to get the selected value
var value = $.trim( this.value ); // $.trim() used to remove space
// from beginning and end
// you may not use
// to get selected option text
var optText = $('option:selected', this).text()
// to get the selectedIndex
var selIndex = this.selectedIndex;
// OR
var selIndex = $(this).prop('selectedIndex');
});
Note
Here, select[id^=selectBox] get select boxes, whose id start with selectBox. You may have something different id.
.change() used for bind the event to those select box.
Read more about
jQuery selectors
jQuery Events
$.trim()
.prop()
you can set an specific attribute for each select so:
<select id="selectBox1" val='1'>
</select>
<select id="selectBox2" val='2'>
</select>
<select id="selectBox3" val='3'>
</select>
<select id="selectBox4" val='4'>
</select>
and then bind onchange event like this:
$("select").change(function(){
var val = $(this).attr("val");
if (val == '1')
{
//logic for first select change
}
else if (val == '2')
{
//logic for second select change
}
else if (val == '3')
{
//logic for third select change
}
// and so on...
});
hope that helps.