I have sibling SELECT menu elements like so ...
<select name="country1" class="country">...</select>
<select name="state1" class="state">...</select>
The names will change (e.g. "country1" ... "countryn"), but the classes associated with the elements (e.g. "country" and "state") will not. In my Javascript, I want to rewrite this line ...
var firstOption = $("#state option:first-child");
given that I have a country element, $(countryElt), and I want to say, store the first option of the sibling ".state" element of the $(countryElt). How do I write that?
$('.state option:first')
.parent()
.siblings('.country')
.find('option:first');
HI Dave, per your comments, we had better add a ID in the second select, which is as follows.
<select name="state1" class="state" id="state">...</select>.
So the code will be changed to
$('#state option:first')
.parent()
.siblings('.country')
.find('option:first');
You can use parent() and siblings(), like this:
var stateFirstOption = $("#state option:first");
var countryFirstOption = $stateFirstOption.parent().siblings('.country').find('option:first');
You can do:
$(countryElt).next("select.state option:first")
Related
I have many inputs where to dynamically change the value of the name attribute, for example:
Select
<select class="form__input form__select select optional" id="js-customer-field" name="customer[customer_food_attributes][16321232322354][customer_id]"><option value="">Select</option>
...
<select class="form__input form__select select optional" id="js-customer-field" name="customer[customer_food_attributes][023912321331123][customer_id]"><option value="">Select</option>
I would like to take the value to apply to an event, but since the id's are random I don't know how to capture them
on this name attribute or any with random id:
"customer[customer_food_attributes][023912321331123][customer_id]"
$("customer[customer_food_attributes][023912321331123][customer_id]").on('change'), function(e, item) {...})
I would be very grateful if someone could help me build the attribute dynamically
Thank you for your time in reading me.
It is not really clear to what you are trying to do. Could you maybe clarefy a little bit?
Are you trying to change the name attribute of the select elements?
Or do you want to bind an event to all select elements?
If the latter, I would do something like this (assuming you want to trigger the event on a value change):
$(".form__select").on("change", function(){
// Get the name attribute
let name = $(this).attr("name");
// Do whatever you like, depending on the value of name
// ...
};
You could just listen to change events from any select elements and check if the name matches the pattern.
This can be done with/without jQuery.
// using jquery
$('select').on('change', function(e) {
const regex = /customer\[customer_food_attributes\]\[(\d+)\]\[customer_id\]/;
const match = e.target.name.match(regex);
if(match){
const id = match[1];
// here is your id
// do something with it
}
});
// using vanilla js
document.addEventListener('change', function(e) {
const regex = /customer\[customer_food_attributes\]\[(\d+)\]\[customer_id\]/;
const match = e.target.name.match(regex);
if(match){
const id = match[1];
// here is your id
// do something with it
}
});
Using jQuery, I am trying to get the data attribute of the following...
54
var myid = jQuery("active").data("id");
Buit this is giving me an undefined error, where am I going wrong?
Missing "." before class selector. You need to do something like this to get the id attribute:
$(".active").attr("id");
Refer: https://api.jquery.com/attr/
active will select <active> elements, if you want to get elements that have this class name use .active.
Here is an example:
jQuery(".active")
You forgot to use class selector (.) .Moreover Class selector is not suited when you are looking to have multiple elements with same class (it will always return the first element).
var myid = jQuery(".active").data("id");
console.log(myid)
// if you have multiple elements with same class
jQuery(".active").each(function() {
let myid = $(this).data("id");
console.log(myid)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
54
55
var myid = jQuery(".active").data("id");
console.log(myid)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
54
You were missing a "." in the selector - to tell jQuery you are selecting a class.
if you are accessing class then add '.'(dot).
you code would be .
54
var myid = jQuery(".active").data("id");
To find the attribute value of any tag you may use attr() method on the tag. Inside the attr() method you have to pass the custom data tag like data-{attribute-teag-name}
There are four different ways to get the result:
$(document).ready(function(){
var id = $("#custom").attr("data-customid");
console.log("attribute value with id -- ",id);
var id_1 = $(".active").attr("data-customid");
console.log("attribute value with class -- ",id_1);
var id_2 = $(".active").data("customid");
console.log("attribute value with class and data method -- ",id_2);
var id_3 = $("#custom").data("customid");
console.log("attribute value with id and data method -- ",id_3);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
54
There is "." missing before class selector, You can get the data-id attribute value by:
$(".active").attr("data-id");
or
$(".active").data("id");
Getting data- attribute value by class so you have to use "." and by id "#" before the tag-name
Reference:
https://api.jquery.com/attr/
https://www.tutorialspoint.com/jquery/jquery-selectors
You call <active> elements by Jquery("active")
Try
var myid = Jquery(".active").data("id");
I would like to use select multiple tab in html like
<select name="foo" multiple>
<option value="all">option1</option>
<option value="all">option2</option>
<option value="all">option3</option>
</select>
How can I get data in javascript from this multiple select tab
I tried
var foo = [];
$('#foo:selected').each(
function(i,selected) {
foo[i] = $(selected).text();
}
);
But no luck, it doesn't work. It shows foo.length==0
What is the correct way to do this? Thanks!
$('#foo:selected')
should be
$('#foo option:selected')
Selected attribute is a property of the options inside select and not select element.
Secondly you have no element with id="foo"
$('[name=foo] option:selected') // for this case
$('#foo:selected')
This tries to find instances of #foo which are selected. But that's the select element itself, not the options therein. Try with the options:
$('#foo option:selected')
Update: It looks like the first part of the selector is wrong, too. You don't actually have an element of id foo so #foo won't find anything. What you have is a select element with the name foo. So something like this instead:
$('select[name="foo"] option:selected')
Try this instead:
var foo = [];
$("[name='foo']").change(function () {
$("[name='foo'] option:selected").each(function (i, selected) {
foo[i] = $(this).text();
});
})
.trigger('change');
I need to be able to change certain option from select menu to be as default (start) value when I do something.
For example when I declare it, English language is default value.
How to change that with the code and not with the click.
<form id="form1" name="form1" method="post" action="">
<select name="websites1" id="websites1" style="width:120px" tabindex="1">
<option value="english" selected="selected" title="images/us.gif">English</option>
<option value="espanol" title="images/es.gif">Espanol</option>
<option value="italian" title="images/it.gif">Italiano</option>
</select>
</form>
In the body tag I have declared:
<script type="text/javascript">
$(document).ready(function() {
$("body select").msDropDown();
});
</script>
I am using this SCRIPT
I have tried all of the bellow examples and none this is good for me.
What else can I do change default select value.
This is working for me as mentioned in the docs:
$('#websites1').msDropDown().data('dd').set('selectedIndex',2);
This will select italian ;)
/edit:
Keep in mind that #Patrick M has a more advanced approach and he posted his approach before I posted mine ;)
If you are having weird css issues like I did, try this undocumented stuff:
$('#websites1_msa_2').click(); // this will also select the italian
As you can see the id is generated by $('#websites1_msa_2') the id of the selectbox plus the $('#websites1_msa_2') index of the option item.
A bit hacky but works ;)
So you could then define a JavaScript-Function like this:
var jQueryImageDD_selectByName = function(name) {
var children = $('#websites2_child').children();
for(var i=0;i<children.length;i++) {
var label = children[i].getElementsByTagName('span')[0].innerHTML;
if(label === name) {
children[i].click()
}
}
};
And then use it like this:
jQueryImageDD_selectByName('Italiano'); // will select Italiano :)
He does say
You can set almost all properties via object
So, just guessing from the documentation examples he provides on that page... I would think adapting this:
var oHandler = $('#comboboxid').msDropDown().data("dd");
oHandler.size([true|false]);
//Set or get the size property
To the .value property might work. So for you to set the language to Italian, try
var oHandler = $('#comboboxid').msDropDown().data("dd");
oHandler.value('italian');
// Or maybe the way to do it is this:
oHandler.set('value', 'italian');
// Or maybe 'value' shouldn't be in single quotes
//set property
If that doesn't work, you could try looping over all the properties, getting and comparing the value at each index and, when you find it, setting the selected index to that property name.
var languageSelect = $('websites1');
var oHandler = $('#websites1').msDropDown().data("dd");
for(var index = 0; index < languageSelect.length; index++) {
var option = oHandler.item([index]);
if(option == 'italian') {
oHandler.set("selectedIndex", index);
break;
}
}
One of those should work. If not, you're pretty much just going to have to wait for a reply from the author.
You can either use selectedIndex to change the index of the selected option (0 being the first)
document.getElementById("websites1").selectedIndex = 1; //espanol
, or you can use value to change the text of the value (and if there's a match, it will change it automatically).
document.getElementById("websites1").value = 'espanol';
use selectedIndex. See this page. A select control has an options property, which basically is an array of option elements. The first element in your select is options[0], english, so:
document.getElementById("websites1").selectedIndex = 0; //=> english
You can also make the first option selected by default using:
document.getElementById("websites1").options[0]
.defaultSelected = true; //=> english by default
working option (1. destroy msdropdown, 2. select by value, 3. set up msdropdown)
put this code somewhere in js:
jQuery.fn.extend({
setValue: function(value) {
var dd = $(this).msDropdown().data("dd");
dd.destroy();
$(this).val(value);
$(this).msDropdown();
}
});
setting value:
$('#selectorOfmsDropDown').setValue('opt10');
or just:
$("#selector").msDropdown().data("dd").setIndexByValue(newvalue);
i have a multiple select tag, look at script please
<select multiple="multiple" size="5" id="cities_select">
<option value="1">city1</option>
<option value="2">city2</option>
<option value="3">city3</option>
<option value="4">city4</option>
<option value="5">city5</option>
<option value="6">city6</option>
................................
</select>
and jquery script:
$("#supply_cities_select").change(function()
{
var i = 1;
$('#supply_cities_select :selected').each(function(u)
{
src += '&c'+i+'='+$(this).val();//generates the string like &c1=1&c2=2&c3=7...
i++;
});
})
i need my string not to have elements greater then 5
example:
if i allready have 5 selected elements, my string looks like
&c1=2&c2=3&c3=5&c4=6&c5=7
now if one more option will be selected, i need to get the string
&c1=3&c2=5&c3=6&c4=7&c5=8
if be short, i need to remove selected attribute of first selected element.
(but i can't use .first here, because it can be element N8 the first selected)
how can i do it?
Thanks a lot.
UPDATE
var a = $("#supply_cities_select :selected").length;
if(a > 5)
{
$("#supply_cities_select :selected:lt(1)").attr("selected",false);
}
it just remove the firs selected option, isn't it?
You can do this a little simpler usign .map() and :lt() like this:
var src;
$("#supply_cities_select").change(function() {
src = $("#supply_cities_select :selected:lt(5)").map(function(i) {
return '&c'+(i+1)+'='+this.value; //i starts at 0, so add 1
}).get().join('');
});
You can try a demo here. The :lt() selector gets the first 5 (less than 5, 0-based, so (0-4), then we're using .map() to get the values into an array, then just calling .join() to get a string of that array added together.
For the update: to get the last 5 elements it's better to use .slice(), like this:
var src;
$("#supply_cities_select").change(function() {
src = $("#supply_cities_select :selected").slice(-5).map(function(i) {
return '&c'+(i+1)+'='+this.value; //i starts at 0, so add 1
}).get().join('');
});
You can give it a try here.