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
Related
Here is my script tag
<script
src="https://checkout.razorpay.com/v1/checkout.js"
data-key="abcd"
data-amount="100"
data-buttontext="Pay with Razorpay"
data-name="Seven Atara"
data-description="Website Purchase"
data-image="https://your-awesome-site.com/your_logo.jpg"
data-prefill.name="Harshil Mathur"
data-prefill.email="support#razorpay.com"
data-theme.color="#F37254"
id="paymentWidget"
></script>
How can i change the value of data-amount="100" to my desired value
I tried like
document.getElementById("paymentWidget").attr("data-amount") = total
But it is showing error like
document.getElementById(...).attr is not a function
How can i fix this and set values dynamically ?
First include reference to the jquery library file.
Then rewrite the code as follows,
$('#paymentWidget').attr("data-amount",desired-value);
Your question is tagged with Jquery, but you're using plain JavaScript to get and element from the DOM
Try changing it to use a Jquery selector and setting the attribute correctly
$('#paymentWidget').attr('data-amount', total)
The reason your code isn't working is because you're trying to use the Jquery method .attr on something which isn't a Jquery object.
Alternatively you could use .data
$('#paymentWidget').data('amount', total)
The major difference is that .data will not change the DOM
Try this
document.getElementById('paymentWidget').setAttribute('data-amount', total)
Right function is setAttribute, check its syntax bellow:
document.getElementById("paymentWidget").setAttribute('data-amount', total)
You can use the dataset. Data set is used when your attribute begins with data-.
In your example:
document.getElementById("paymentWidget").dataset.amount = total;
Support for this is IE>11
For more support use the element.setAttribute("attribute", "value")
Read more on MDN:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset
im working with my first webapp, Im using ajax parsed object to add dynamic content to one specific .html... while doing so, I found an issue with adding data-* attribute to every option on a select dropdown... when the change function from JQuery executes, it returns undefined.
Here is my ajax function, (I know its not the best way to do it).
ajaxPost("link/x.php",{},function(result){
var json=JSON.parse(result);
var resultado=json.response;
if(json.error==0){
var estadosString='<option value=""></option>';
var cont=0;
for(estado in resultado){
estadosString+=('<option value="'+resultado[estado].nombre+'">'+resultado[estado].nombre+'</option>');
}
$('#estados').html(estadosString);
cont=0;
$('#estados option').each(function(){
$(this).attr('data-id',cont);
$(this).data('id',cont++);
});
}else{
alert("No hay estados");
}
});
The data-id attribute is sucefully added to each option, the issue starts when I use this code to get data-id on change select option.
$('#estados').on('change',function(){
alert($(this).data("id"));
});
It always return undefined, anyone can help me? Thanks..!
The value of this in that "change" handler will be the <select> element, not the <option> it's set to. You can find the option element via the select element's selectedIndex property, or via jQuery.
There's no reason to set the "data-id" attributes either; just set the value via .data().
I wanted to put an id in my element's parent element. Below is my code:
<div>
<div id="child"></div>
<div>
Im aware that jquery has a way to select a parent element , but I dont know how what method shall I use to put an id to it. Below is my jquery code:
div_resizable = $( "#child" ).parent();
div_resizable.id = "div_resizable";
Above code doesnt work with me. It doesnt throw an error, but no changes had taken effect. Any solution to my problem?
For achieve what you want, you can use the jquery attr:
$("#child" ).parent().attr('id', 'newID');
Or you can use the prop:
$("#child" ).parent().prop('id', 'newID');
And you can check the difference between the two here: difference between prop() and attr()
Of course div_resizable.id = "div_resizable" doesn't work. div_resizeable is an jQuery array and you are trying to assign id to it.
Try .attr instead:
$("#child").parent().attr({id: "div_resizable"});
To set a property on the first element inside a jQuery result object:
div_resizable = $( "#child" ).parent()[0];
// ^^^
div_resizable.id = "div_resizable";
This picks the first Element from the result so that you can directly access the property.
Or:
$('#child').parent().prop('id', 'div_resizable');
Use the .prop() helper method to accomplish the same thing.
i want to use a input box from SELECT2(jQuery Plugin) and want to send it with PHP Post to the server.
How do i access these Elements (A, Adolf, B)?
Thanks
$('.select2-search-choice div');
if you want to get the text of the elements, then use $('.select2-search-choice div').text();
If you use Select2 (http://ivaynberg.github.io/select2/) it overrides <select> element.
So probably you use like this:
<select id="my-select"><option>...</option></select>
And in JS:
$("#my-select").select2();
This way - if you want to read current value just use:
$("#my-select").val();
or using Select2 API:
$("#my-select").select2("val");
If you need to get all values from <option>'s - you can do it like this:
$("#my-select option").map(function() {return $(this).val();}).get();
You can loop through $('li.seleact2-search-choice').children('div'); or simply $('.select2-search-choice div');
To get an Array of the values use the API from select2:
var data = $("#YourSelect2Element").select2("val");
You have to change the selector in the selector you used to create the select2 input.
See the docs.
I have been searching for the solution for this for a while so I hope I can get some help now. I am attempting to figure out whether a programmatically added checkbox is checked using jquery. The HTML code of the checkbox is below:
<td>
<input type="checkbox" name='ismanual' id='ismanual' class="checkbox">
</td>
And I am doing it using the following jquery code:
var ismanual = document.getElementById("ismanual").val();
I have attempted using #ismanual as the selector, but that didn't help. Any idea where I have gone wrong?
If you're using document.getElementById("ismanual") you should use .checked instead of .val()...
var ismanual = document.getElementById("ismanual").checked;
For jQuery use...
var ismanual = $("#ismanual").is(':checked')
Where you have gone wrong: if you want to use val(), you need to use it on a jQuery object. getElementById() gives you a DOM element but not a jQuery object. To get a jQuery object you need to find the element using a jQuery selector like this:
jQuery('#ismanual')
You can then use jQuery's :checked selector and the .is() function on that object:
var isManual = jQuery('#ismanual').is(':checked');
.val() is a jQuery function. It will not work with DOM style element selection.
To get value using .getElementById(), you must use .checked like,
var ismanual = document.getElementById("ismanual").checked;
.val() will work when you are selecting the element using jQuery like,
$("#ismanual").val();