<select class="tmcp-field tillagg-width tm-epo-field tmcp-select"
name="tmcp_select_30"
data-price=""
data-rules=""
data-original-rules=""
id="tmcp_select_75"
tabindex="75">
<option value="5 (480 mm)_0" etc.......
To get value of this element, currently I am using this piece of code:
document.getElementById("tmcp_select_75").value
It works well, but how can I get value of element using "tmcp-field tillagg-width tm-epo-field tmcp-select" seen it top row of first code sample? Thanks :)
Use querySelector() or querySelectorAll() or getElementsByClassName()
// Gets the first match's
document.querySelector(".tmcp-field.tillagg-width.tm-epo-field.tmcp-select")
// Gets a collection of the selects;
document.querySelectorAll(".tmcp-field.tillagg-width.tm-epo-field.tmcp-select")
// Gets a collection of the selects;
document.getElementsByClassName("tmcp-field tillagg-width tm-epo-field tmcp-select")
jQuery
$(".tmcp-field.tillagg-width.tm-epo-field.tmcp-select")
You don't need jQuery for this. If I'm reading you right, you want to select the element using its class instead of by ID, as you're doing right now. Use document.querySelector:
document.querySelector('.tmcp-field.tillagg-width.tm-epo-field.tmcp-select');
You probably don't need to select for all of those classes, so remove any that you don't need to narrow down the result.
Related
I am trying to add more than one attr() value when using append in a dropdown in jQuery.
This is working fine:
$('#twostages').append($('<option/>').attr("value", option.stage).text(option.stage));
And I can access the value using:
document.getElementById("twostages").value
However, when I try this code:
$('#twostages').append($('<option/>').attr({ "value": option.stage, "matone": option.matone }).text(option.stage));
I am not able to retrieve the value or matone using the document.getElementById("twostages").value or document.getElementById("twostages").matone
I got the idea of the above code from this topic: jQuery: Adding two attributes via the .attr(); method
Any help would be greatly appreciated.
Thanks.
matone is a property added on options.So you can't access it directly.
you need to check first the selected option and then get it's corresponding matone value using .attr()
Working snippet:-
$('#twostages').append($('<option/>').attr({ "value":"stage1", "matone": "mymetion" }).text("stage1"));
console.log($('#twostages').val());
console.log($('#twostages').find(':selected').attr('matone'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="twostages">
</select>
Reference:-
.attr()
:selected
Note:- Standered practice is to use data-attributes for custom attributes
I have a this select dropdown:
<select id="category">
<option value="cat1">Category 1</option>
<option value="cat2">Category 2</option>
</select>
and I have this code that everytime I select something form the dropdown it takes the value and find the same class and show it on the last line
$('#category').change(function () {
var selected_category = $(this).val();
$('#sub-category').find('.option').hide();
$('#sub-category').find('.'+selected_category).show();
});
I just want to change instead of class so it will find the attribute rel
** edited **
You definitely don't need jQuery for this. Here's the code to find all option tags with a rel attribute of "sub-cat1":
document.querySelectorAll('option[rel="sub-cat1"]')
The above will work in IE8 and up, which should satisfy all browsers you need to support. The jQuery solution is similar, and uses the same selector string:
$('option[rel="sub-cat1"]')
Furthermore, you don't need to add a class of "option". Simply select using the option tag name.
There can be an alternate way to your answer.
Using jquery try ,
$ (".classname").each(function(){
//iterate over similar *classname* elements one by one
$(this).someFunc(); //it will help you to preform operation at current value while iteration
});
With rel if you want to iterate over rel tag values , try
$("[rel='sub-cat-1']").each(function(){
//Some operation
});
Here is my HTML:
<div class="tour" data-daily-price="357">
<h2>Paris, France Tour</h2>
<p>$<span id="total">2,499</span> for <span id="nights-count">7</span> Nights</p>
<p>
<label for="nights">Number of Nights</label>
</p>
<p>
<input type="number" id="nights" value="7">
</p>
</div>
This is my incorrect code for changing the test of the span element to read what I typed into the number input.
$(document).ready(function() {
$("#nights").on("keyup", function() {
$("#nights-count").text($("#nights").val());
});
});
This is the correct code:
$(document).ready(function() {
$("#nights").on("keyup", function() {
$("#nights-count").text($(this).val());
});
});
Why do I need to use self and not #nights for this to work?
If you have multiple id with name #nights in your document then default it select first one id with id #nights. where this will indicating the current selected DOM element instead of #nights id. If you use this it indicate to current selected DOM element, that's why you get correct output in your case there is multiple id with #nights.
It should work just fine unless #nights is not a unique ID. For example if there are multiple "tour" divs each having a #nights element. That said, $(this) is better because it doesn't require jQuery to go and parse the DOM again...
The issue is that you have more than 1 element with the id nights. Your first block of code works: http://jsfiddle.net/fomd990c/
If you have another element with the id nights it doesn't: http://jsfiddle.net/fomd990c/1/
It is generally a good idea to restrict a particular id to only one element.
I am cloning some form elements and want to generate for them dynamic ids so I can acces their content later on, but I don't really know how to do that, I'm a noob with Jquery/Javascript, by the way.
My html:
<tr>
<td>
<label for="ability">Ability</label><br>
<div id="rank_ability" name="rank_ability">
<select name="ability" id="ability">
<option value=""></option>
<option value="hexa">Test</option>
</select><br>
<label for="range_ability_min">Range:</label>
<input type="textbox" name="range_ability_min" id="range_ability_min" class="small_text" value="0" /> -
<input type="textbox" mame="range_ability_max" id="range_ability_max" class="small_text" value="0" /><br>
</div>
Add Ability<br><br>
</td>
</tr>
My JS:
$(document).ready(function () {
var element, ele_nr, new_id;
$('.rank_clone').click( function() {
element = $(this).prev();
ele_nr = $('div[name="'+element.attr('name')+'"]').length;
new_id = element.attr('name') + ele_nr;
element.clone().attr('id', new_id).attr('name', new_id).insertAfter(element);
});
});
I setup a jsfiddle with what I got here: http://jsfiddle.net/xjoo4q96/
Now, I am using .prev() to select the element to clone which leads to those repeated 1 in the id/name attributes, how could I select it in another way (to mention: I really need to use 'this' because I need this little script in like 3 places, so I don't want to write it for an element with a specific id/class).
Also, I am counting only the element with the base name attribute so .lenght yelds 1 all the time, how would I go around counting all of them ? I guess I have to place them in another div or something but I don't know how would I go around couting them even then.
And, at last, how would I go around changing all the name/id attributes of the elements I have in the div ?
I'd appreciate any help. Thanks.
you can put the template in a hidden div like #tmpl, then clone and set the id attr, e.g.
$('#tmpl').children().first().clone().appendTo('#target').attr('id', 'the_generated_id');
Update
Demo of the template way: http://jsfiddle.net/xjoo4q96/1/, though it would be quite easy to adjust the code to clone the first component that already existed.
BTW, principally, id should be unique, thus the sub-element in the cloned component should use other attribute, like class or certain data- attribute, like those used in the updated fiddle.
Also you might want to call event.preventDefault() as you're clicking an <a>
You are searching already with the wrong name, since it still has the number attached. So delete it first, search for element which have a name attribute starting with this name and then use this base name to create a new one.
$(document).ready(function () {
var element, ele_nr, new_id, base_name;
$('.rank_clone').click( function() {
element = $(this).prev();
base_name = element.attr('name').replace(/[0-9]/g, '');
ele_nr = $('div[name^="'+base_name+'"]').length;
new_id = base_name + ele_nr;
element.clone().attr('id', new_id).attr('name', new_id).insertAfter(element);
});
});
And to answer your last question: you can not go around changing all ids of inner elements, it would be invalid HTML. In principal you can do the same with every id, like adding a number. If you have to do the same with all the name attributes depends on what you want to do exactly. If you have to distinguish between the first and second input, which I suggest, you have to change them too.
try to use cloneJs, it's clone ids, names input, and parametre inside functions ids of input must be like id_foo_1, id_foo_2 ,,,, and name be like inputName[0][foo], inputName[1][foo] https://github.com/yagami271/clonejs
on my site is a form which has multiple checkboxes with the same name:
<span class="selection"><input type="checkbox" name="product" value="Hard Enamel" />Hard Enamel</span>
<span class="selection"><input type="checkbox" name="product" value="Soft Enamel" />Soft Enamel</span>
<span class="selection"><input type="checkbox" name="product" value="Metal Relief" />Metal Relief</span>
<span class="selection"><input type="checkbox" name="product" value="Printed With Epoxy" />Printed With Epoxy</span>
In my Javascript, I assign these to a variable and have an onclick function using JQuery. With this I can still run JQuery functions no problem, e.g. products.css("display","none") works.
But when trying to select a particular checkbox within products it hits back with an error.
Here is my JS:
var products = $("input[name=product]").click(function(){selectProduct()});
products.get(0).css("display","none");
The above doesn't work, and I get the error badges_calc.js:9TypeError: 'undefined' is not a function (evaluating 'products.get(0).css("display","none")')
How can I fix this? I'm rather beginner.
Cheers
get() returns DOM element try use eq instead. DOM element does not have css method it is the jquery Object that has it. eq(0) will give you the first element in the collection as a jquery object.
products.eq(0).css("display","none");
And if you are really looking to hide the span along with the check box then use:
products.eq(0).closest('span').css("display","none");
otherwise it will leave the span with the text there itself, by just hiding the checkbox.
.get() returns a raw DOM object.
You want .eq(0), which returns a jQuery object with only one element.
Try this:
var products = $("input[name=product]");
products.click(function(){selectProduct()});
products.eq(0).css("display","none");
When you use .get() you will get a raw DOM element and cannot use jQuery's methods, so you cannot use .css()
Use closest or parent to hide the selected input's parent.
var products = $("input[name=product]").click(function(){selectProduct(this)});
var items = [];
function selectProduct(self){
$(self).closest('span').hide('slow');
items.push($(self).val());
console.log(items);
}