How to access data-attributes of HTML elements using javascript [duplicate] - javascript

This question already has answers here:
PURE JS get selected option data attribute value returns Null
(4 answers)
Closed 4 years ago.
I have a dropdown menu in my form. Each option has 3 data-attributes associated with it. When one option is selected I call a function that sets the values of hidden html objects to the value of each data attribute so I can pull that information on the next page. However, the value of the data-attributes keeps coming up as "undefined". What am I doing wrong?
<script>
function change_charge(x)
{
alert (x.dataset.amount);
}
</script>
<select name="description" id="description" onchange="change_charge(this)">
<option value="Test" data-amount="10.00" data-type="charge" >TEST </option>
</select>
I expect the alert to say the value of data-amount but instead it says "undefined"
I have also tried:
alert (x.getAttribute('data-amount'));
But that returns "null".

x is the <select>, not the <option>. The select has no data- attributes.
If you want the option, use
var option = x.options[x.selectedIndex];
console.log(option.dataset.amount);

This answer shows how you can get a custom attribute from JavaScript.
Summary: you can use getAttribute()
x.getAttribute("data-amount");
EDIT:#James also makes a good point, which is x is the selector, not the option. Thus you will probably need a combination of our two answers:
x.options[x.selecetdIndex].getAttribute("data-amount");

Related

Constraint validation to not match a constant value [duplicate]

This question already has answers here:
Can I apply the required attribute to <select> fields in HTML?
(13 answers)
Closed 5 years ago.
I'm trying to make a pattern-matching using HTML5 constraint-validation to check if a value is not equal to a given value.
<select pattern="(?!ZZZ)">
<option value="ZZZ">Please select a nation™</option>
...
<option value="GER">Germany (GER)</option>
...
<option value="ZIM">Zimbabwe (ZIM)</option>
</select>
In case the user has selected the default value ZZZ it should match and show the error-message (which is done via JavaScript).
I tried different online tools to check whatever pattern I use but nothing.
I simply need to check if the value does not match a constant string ZZZ but I don't get it.
Already tried to go the other way around so it has to match ZZZ and invert this regex somehow. But even there I get stuck.
You're overthinking it. :-) Just make the value of that option "" and use required:
select:invalid {
color: red;
}
<form>
<select required>
<option value="">Please select a nation™</option>
<option value="GER">Germany (GER)</option>
<option value="ZIM">Zimbabwe (ZIM)</option>
</select>
</form>
From the WHAT-WG HTML spec for required:
If a select element has a required attribute specified, does not have a multiple attribute specified, and has a display size of 1; and if the value of the first option element in the select element's list of options (if any) is the empty string, and that option element's parent node is the select element (and not an optgroup element), then that option is the select element's placeholder label option.
And so selecting that option does not make the select valid.

Putting value of "select" tag into JavaScript variable [duplicate]

This question already has answers here:
Get selected value in dropdown list using JavaScript
(32 answers)
Closed 6 years ago.
Sample of <select> HTML form element from W3Schools (a bit modified):
<select>
<option value="a">Option A</option>
<option value="b">Option B</option>
/*...*/
</select>
As far as I could see, neither option nor select has id property, so the good old document.getElementById("name of select element").value does not work.
But then, how can I put the value attribute of the option that is selected in the list into a JS variable?
I'm aware that it can be done by a function call, e.g. when I push a button element, but what do I have to write into that function?
Aside from just giving it an id, you can add an onchange event:
<select onchange="yourfunction(this.value)">
...
There are also other ways to access elements in your DOM. For example, assuming this is the only (or first) select on your page you could access its value with a line like this:
var val = document.getElementsByTagName("select")[0].value;
If you don't have an id to work with, the DOM provides a few other APIs that you can use, but probably the most versatile is:
document.querySelector("CSS Selector Here");
So, you could use a selector that finds the select element by the tag name select or by its position in the DOM or by a class name applied to it, etc.
Then, to get the value, you'd write this:
var val = document.querySelector("CSS Selector Here").selectedIndex.value;

Setting element value in Javascript [duplicate]

This question already has answers here:
HTML - attributes vs properties [duplicate]
(2 answers)
Closed 8 years ago.
I have the below element:
<input type="text" value="" tabindex="1" size="15" onblur="UpCaseSearch(this)" name="name">
which is an empty text field.
I want to set text into that field and I can successfully do that using a command like that (when I say successfully I mean that I can see that field populated with text test:
window.frames[1].document.getElementsByName('name')[2].value = "test"
I have 2 questions however:
When I look at that element on the page I see that the value attribute is still empty "". Why is that? Where is the actual text that I can see in that field is coming from?
If I try the below command, it will actually set the value but then the field remains empty:
window.frames[1].document.getElementsByName('name')[2].setAttribute('value', 'test')
So it looks like that's not the same value in both cases. Is that right?
Try this:
window.frames[1].document.getElementsByName('srchsnam')[2].value = "Test"
Let me know if it worked!
In short, the value attribute in source-code (and dom) serves as 'defaultValue'.
For example, imagine this input-field (which is a common way to use this functionality):
<input type="text"
value="your name here"
onfocus="if (this.value===this.defaultValue) this.value='';"
onblur="if (this.value==='') this.value=this.defaultValue;" >
In other words, to set the default value in html-markup (<input value="your_value" type="text">) and from javascript you set the value-attribute (using the methods: var val=elm.getAttribute('value') and elm.setAttribute('value', val).
This is also why (as you have seen) these attributes propagate to the element's outerHTML (and thus the element's parent innerHTML).
However to get/set the element's current value property you use: var val=elm.value and elm.value=val.
Sidenote: Almost the same goes for a textarea: you can use .defaultValue on a textarea to retrieve it's textContent (but you'd override/change that by setting it's innerHTML) while you get/set the current value using elm.value.
Hope this helps!

Changing the selected option with jQuery [duplicate]

This question already has answers here:
Change the selected value of a drop-down list with jQuery
(18 answers)
Closed 8 years ago.
I'd like to change the selected option with jQuery.
<select name="nameSelect" id="idSelect">
<option value="0">Text0</option>
<option value="1">Text1</option>
<option value="2" selected>TextSelected1</option>
</select>
I'm trying with $("#idSelect").val(); or similar, but it doesn't work.
Regards
pass the value which needs to be set as parameter in .val() :
$("#idSelect").val('0');
That does work, but you need to include the value of the option you want selected as a parameter to val(), e.g.:
$("#idSelect").val('1');
Add the value in the val as
$("#idSelect").val(0);
You can simply change the value of the select. And I would suggest it to use the select[name=NAME]-Tag..
$('select[name=nameSelect]').val(1);
Greetings from Vienna

How to change a radio button value [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
how to check a radio button with jQuery?
How to change a radio button value.
jQuery('input:radio[name=search][id=search-damages]').checked = true;
i have tried this but it is not working
<input type="radio" name="search" id="search-vehicle" value="search-vehicle" checked>
<input type="radio" name="search" id="search-damages" value="search-damages">
How to change a radio button value?
checked property doesn't change the value of radio button. note that checked property is one the DOM INPUT Element properties and not one of the jQuery object properties(by selecting an element using jQuery, a jQuery object is created). If you want to change this property you should first convert the jQuery object into a DOM Element object.
$('#search-damages')[0].checked = true;
or use the jQuery object's prop() method:
$('#search-damages').prop('checked', true)
If you want to change the value of an input you can use the jQuery val() method:
$('#search-damages').val('new value');
I'm a fan of "use jQuery when reduce complexity, use JS in other cases", so I would go for:
$("#search-damages")[0].checked = true;
Otherwise, if you prefer use jQuery syntanx, you could use:
$("#search-damages").prop("checked", true);
See: http://api.jquery.com/prop/
Try this:
$('#search-damages').attr('checked','checked');

Categories