How can I get an HTML5 data value from a select option? - javascript

Is it possible to use jquery to get an html5 data attribute from a select option?
<select id="change-image">
<option value="cool" data-image="myimage.jpg">Cool</option>
</select>
$("#pet-tag-id").change(function() {
var src = $("#change-image").data("image");
$("#image-preview").attr("src", src);
});
<img id="image-preview">

Yes.
You even did it in the correct manner. jQuery will pull HTML5 data attributes into its internal expando data object for elements. So you can access them just by name.
The only thing that is incorrect is, that you don't call .data() on the correct element. You're calling it on the <select>, but you need to grab the selected option element. Like
var src = $("#change-image option:selected").data("image");

$("#change-image").change(function() {
var data_image = $(this).children('option:selected').attr('data-image');
});
​

Related

JQuery selector does not work in dynamically created content?

I am trying to retrieve the .html() .val() or something else within a html element, this is my html code (generated dynamically):
<div class="presupuesto"><h2 class="precio" id="precio" value="1202">1.202,00 €</h2>
I need the .val() attribute!
With JQuery and JavaScript I want to show, what option from a select has been selected and then show the information about h2 tag (price). This is my JS code:
$('select').on('change', function (e) {
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
alert(valueSelected);
alert(("#precio").val());
});
The first alert(valueSelected) works well, but the second one triggers a TypeError
Thanks in advance!
As you said that you have dynamically generated elements. Then You need to use event-delegation:-
$(document).on('change','select',function(){
alert($(this).val()); // to get select value
alert($('#precio').attr('value')); // try to use data-attribute which is standered way
});
Note:- Since <h1>,<h2>..,<div>,<ul><li><p>.... these elements don't have value attribute (In standered way). So use data-attribute option for them like below:-
<h2 class="precio" id="precio" data-value="1202">1.202,00 €</h2>
And then change jQuery code just a bit like below:-
alert($('#precio').data('value'));

Replicate HTML source of a DOM element in current state

On my page there are a few <select> html elements, each of them with multiple <option> values. I would like the same <select> elements to be used in a MapBox description toolkit, which expects me to pass a HTML source into its setHTML method.
The simple way I do it now is:
var tableOption = document.getElementById(selectId);
var html = tableOption.innerHTML;
return "<select>" + html + "</select>";
This works, however it has a drawback of passing the original html source, therefore it does not reflect which option is selected right now. I know I can get currently selected option with value or selectedIndex, and it should be possible to parse the HTML I have obtained and remove and add selected property to a corresponding node in JS, however this seems a bit complicated.
Is there some easier way how to get a HTML source which could be used to construct a copy of a select element with the exact selection state it has now?
I would prefer a solution without jQuery if possible.
You could just wrap your select in another element. Then you'd be able to select it by id, get the parent node, then the parent node's innerHTML. If you want to show which option is currently selected, you can place the selected attribute on it.
document.getElementById('selectId').addEventListener('change', function() {
var opts = this.getElementsByTagName('option');
for (var i = 0; i < opts.length; i++)
opts[i].removeAttribute('selected');
this.querySelector('option:checked').setAttribute('selected', 'selected');
console.log(this.parentNode.innerHTML);
});
<div class="select-wrapper">
<select id="selectId">
<option>Yes</option>
<option>No</option>
</select>
</div>
Just clone the element and then set the selectedIndex - things like event handlers probably wouldn't be copied though
I realize you asked for a simpler solution but I can't think of one much simpler considering it's only 4 lines
Fiddle https://jsfiddle.net/s8mb0mxp/2/
HTML
<select id="original">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<button>
Clone
</button>
<div id="target">
</div>
JS
$('button').on('click', function(){
var $original = $('#original');
var el = $original.clone(); // Clone the object
$('#target').append(el) // Attach the new object to an element
el.find('option')[$original[0].selectedIndex].setAttribute('selected', 'selected')
console.log(el[0].outerHTML)
});

How to get the value of inner attribute of an li using jquery?

I have following code in Java script from which i have to need get the value on an inner attribute of <li>.
<li class="selected" data-val="1">
I have get the tag using
var a = document.getElementsByClassName('selected');
it is providing me <li> whole tag that is fine. But i have to need get the value of data-val attribute (which is within the <li>) that is 1.
How can i get the value of data-val using variable a that is defined.
Please explain..
Here a is a collection object so you need to get the element reference using index then use .getAttribute() to get the attribute value()
var a = document.getElementsByClassName('selected');
var val = a? a[0].getAttribute('data-val') : '';
//another option for modern browsers
// val = a[0].dataset.val
Since you have jQuery, you can use jQuery to select the element and then use data api like
var val = $('.selected').data('val')
With jQuery you can use $(a).attr("data-val").
Without jQuery you can use a.getAttribute("data-val")
Try this approach
var dataValValue = $(".selected").attr("data-val");
It will get data-val attribute from first li from all li with class .selected
There are two ways, using jQuery and the first returned element in a:
$.data(a[0],"val");
$(a[0]).data("val");
Both are equivalent. Sorry, they're not equivalent, since the first one is lower level, and does not process data-* attributes by itself.
There's no need to use .attr() since data-* attributes are processed automatically in the case of the second one.

document.getElementById(" ").src not working?

I want to be able to choose the Battery 9 inside the dropdownlist.
I want the image of Battery 9 to show in the img tag.
Am I doing something wrong?
HEAD
function checkBatteryLife(){
if(document.getElementById('batterylifes').value == 'batterylife9'){
document.getElementsByTagName('batteryID').src = 'battery9.png';
}
BODY
<img alt="" src="" name="batteryID" onclick="checkBatteryLife()">
</br>
<select id="batterylifes" onchange="checkBatteryLife()">
<option name="batteryIMG" value="batterylife9">Battery 9</option>
</select>
The getElementsByTagName method will return a collection of tags by name, such as IMG or SELECT. Passing in the name attribute of a tag will not yield any results.
You should probably use getElementById and pass in the id of the element:
function checkBatteryLife() {
if(document.getElementById('batterylifes').value == 'batterylife9')
{
document.getElementsById('batteryID').src = 'battery9.png';
}
}
..
<img alt="" src="" id="batteryID" onclick="checkBatteryLife()" />
<br />
<select id="batterylifes" onchange="checkBatteryLife()">
<option name="batteryIMG" value="batterylife9">Battery 9</option>
</select>
You can also use getElementsByName which will return a collection of DOM elements with the specified name property, and then iterate through it to find the correct one.
You need .getElementsByName() function instead of .getElementByTagName():
document.getElementsByName('batteryID')[0].src = 'battery9.png';
As .getElementsByName() function returns list,and not a single element, for accessing list's element you need to use [] square brackets.Specifically you need first matched element with name="batteryID", that's why you should use[0].
Firstly, it is not cross-browser compatible to get the value of the selected option by simply reading the value of the select. Instead, first detect the selected option then read ITS value.
var sel = document.getElementById('batterylifes');
if (sel.options[sel.options.selectedIndex].value == 'batterylife9') {
//your code here...
}
Secondly, as many have pointed out, you are mistakenly using getElementsByTagName to reference a single element by its name. You need getElementsByName(), though this is not cross-browser compatible either. Other options:
use jQuery or some other library
if you don't care about old browsers, use the new document.querySelector() method to select the element via CSS syntax
give the image an ID and use getElementById()

Obtain a HTML elements hidden value

I have a HTML element like so:
<select>
<option id="a" hidden"1">Abcdefgh</option
</select>
And, using javascript, I want to retreive the hidden value from the option element.
How do I do this?
var hiddenVal = document.getElementById( "a" ).hidden; // this doesnt work
Not all attributes map directly to properties. You should be able to use the native .getAttribute() to get the value of custom attributes.
var hiddenVal = document.getElementById( "a" ).getAttribute('hidden');
<select>
<option id="a" hidden="1">Abcdefgh</option>
</select>
Well first off your mark up on your HTMl is all off. You are missing an end tag on the element and you would need to put hidden="1" with the equals and quotes. But is hidden even a valid attribute for an option element?? I dont think it is.

Categories