Undefined option name javascript - javascript

I have the following code. But the alert does not show the name of the option, instead it shows "undefined". For value, it shows the correct content.
<select id="test" name="select_decision" onchange="javascript:
var activeText = this.options[this.selectedIndex].value
var activeOption = this.options[this.selectedIndex].name;
alert(activeOption);
">
An example of one option is:
<option value="test" name="test_name">Test</option>
Been looking on google for an answer but cannot find one!

option elements don't have a name attribute, so there's no reflected property for it, so optionElement.name is undefined.
While you could get the value of that attribute via optionElement.getAttribute("name"), in general if you want to add a custom attribute to an element, you should use the data-* prefix.

Try to use htmlElement.getAttribute(attrName). So, in your case try to use
var activeOption = this.options[this.selectedIndex].getAttribute('name');
instead of your
var activeOption = this.options[this.selectedIndex].name;

Related

Changing input type="number" - value changes, but not the front-end number [duplicate]

I had thought these two were the same, but they appear to not be. I've generally been using $obj.attr("value") to work with form fields, but on the page I'm currently building, $obj.attr("value") does not return the text I enter in my field. However, $obj.val() does.
On a different page I've built, both $obj.attr("value") and $obj.val() return the text entered in the form field.
What could account for $obj.attr("value") working as expected in one case but not in another?
What is the proper way to set and retrieve a form field's value using jQuery?
There is a big difference between an objects properties and an objects attributes
See this questions (and its answers) for some of the differences: .prop() vs .attr()
The gist is that .attr(...) is only getting the objects value at the start (when the html is created). val() is getting the object's property value which can change many times.
Since jQuery 1.6, attr() will return the original value of an attribute (the one in the markup itself). You need to use prop() to get the current value:
var currentValue = $obj.prop("value");
However, using val() is not always the same. For instance, the value of <select> elements is actually the value of their selected option. val() takes that into account, but prop() does not. For this reason, val() is preferred.
PS: This is not an answer but just a supplement to the above answers.
Just for the future reference, I have included a good example that might help us to clear our doubt:
Try the following. In this example I shall create a file selector which can be used to select a file and then I shall try to retrieve the name of the file that I selected:
The HTML code is below:
<html>
<body>
<form action="#" method="post">
<input id ="myfile" type="file"/>
</form>
<script type="text/javascript" src="jquery.js"> </script>
<script type="text/javascript" src="code.js"> </script>
</body>
</html>
The code.js file contains the following jQuery code. Try to use both
of the jQuery code snippets one by one and see the output.
jQuery code with attr('value'):
$('#myfile').change(function(){
alert($(this).attr('value'));
$('#mybutton').removeAttr('disabled');
});
jQuery code with val():
$('#myfile').change(function(){
alert($(this).val());
$('#mybutton').removeAttr('disabled');
});
Output:
The output of jQuery code with attr('value') will be 'undefined'.
The output of jQuery code with val() will the file name that you selected.
Explanation:
Now you may understand easily what the top answers wanted to convey. The output of jQuery code with attr('value') will be 'undefined' because initially there was no file selected so the value is undefined. It is better to use val() because it gets the current value.
In order to see why the undefined value is returned try this code in your HTML and you'll see that now the attr.('value') returns 'test' always, because the value is 'test' and previously it was undefined.
<input id ="myfile" type="file" value='test'/>
I hope it was useful to you.
Let's learn from an example.
Let there be a text input field with default value = "Enter your name"
var inp = $("input").attr("value");
var inp = $("input").val();
Both will return "Enter your name"
But suppose you change the default text to "Jose" in your browser.
var inp = $("input").attr("value");
will still give the default text i.e. "Enter your name".
var inp = $("input").val();
But .val() will return "Jose", i.e. the current value.
Hope it helps.
The proper way to set and get the value of a form field is using .val() method.
$('#field').val('test'); // Set
var value = $('#field').val(); // Get
With jQuery 1.6 there is a new method called .prop().
As of jQuery 1.6, the .attr() method returns undefined for attributes
that have not been set. In addition, .attr() should not be used on
plain objects, arrays, the window, or the document. To retrieve and
change DOM properties, use the .prop() method.
In order to get the value of any input field, you should always use $element.val() because jQuery handles to retrieve the correct value based on the browser of the element type.
jQuery('.changer').change(function () {
var addressdata = jQuery('option:selected', this).attr('address');
jQuery("#showadd").text(addressdata);
});
jQuery(".morepost").live("click", function() {
var loadID = jQuery(this).attr('id'); //get the id
alert(loadID);
});
you can also get the value of id using .attr()
this example may be useful:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
</head>
<body>
<input id="test" type="text" />
<button onclick="testF()" >click</button>
<script>
function testF(){
alert($('#test').attr('value'));
alert( $('#test').prop('value'));
alert($('#test').val());
}
</script>
</body>
</html>
in above example, everything works perfectly. but if you change the version of jquery to 1.9.1 or newer in script tag you will see "undefined" in the first alert.
attr('value') doesn't work with jquery version 1.9.1 or newer.
Example more... attr() is various, val() is just one! Prop is boolean are different.
//EXAMPLE 1 - RESULT
$('div').append($('input.idone').attr('value')).append('<br>');
$('div').append($('input[name=nametwo]').attr('family')).append('<br>');
$('div').append($('input#idtwo').attr('name')).append('<br>');
$('div').append($('input[name=nameone]').attr('value'));
$('div').append('<hr>'); //EXAMPLE 2
$('div').append($('input.idone').val()).append('<br>');
$('div').append('<hr>'); //EXAMPLE 3 - MODIFY VAL
$('div').append($('input.idone').val('idonenew')).append('<br>');
$('input.idone').attr('type','initial');
$('div').append('<hr>'); //EXAMPLE 3 - MODIFY VALUE
$('div').append($('input[name=nametwo]').attr('value', 'new-jquery-pro')).append('<br>');
$('input#idtwo').attr('type','initial');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="hidden" class="idone" name="nameone" value="one-test" family="family-number-one">
<input type="hidden" id="idtwo" name="nametwo" value="two-test" family="family-number-two">
<br>
<div></div>
jquery - Get the value in an input text box
<script type="text/javascript">
jQuery(document).ready(function(){
var classValues = jQuery(".cart tr").find("td.product-name").text();
classValues = classValues.replace(/[_\W]+/g, " ")
jQuery('input[name=your-p-name]').val(classValues);
//alert(classValues);
});
</script>
If you get the same value for both property and attribute, but still sees it different on the HTML try this to get the HTML one:
$('#inputID').context.defaultValue;
In attr('value') you're specifically saying you're looking for the value of an attribute named vaule. It is preferable to use val() as this is jQuery's out of the box feature for extracting the value out of form elements.
I have always used .val() and to be honest I didnt even know you could get the value using .attr("value"). I set the value of a form field using .val() as well ex. $('#myfield').val('New Value');

Extract value from html select tag using JavaScript

I am getting whole select tag as a value from my code, in order to do work around the value i need to extract the value from my select tag,as this tag is dynamically created by the code.
Below is the value i am getting. How can i extract this using java script.Thanks for your help.
rowId[0].QValue = "<select id="Type112" class="GridList" rownumber="0" value="Q1 Only" ><option></option><option value="1" selected="selected">Q1 Only</option><option value="2">Q2 Only</option></select>"
The proper way to do this would be to select the element from the DOM with one of the selection functions. In this case, I prefer document.querySelector:
var type112 = document.querySelector('#type112');
The # means 'id', and you can pass any combination of valid CSS to document.querySelector.
Then, to produce the value of this element, simply call
type112.value
This will give you the text value of the currently selected option within the select element.
Based on your comment, I'm sensing that perhaps you have the text of an element and want to parse out the id? If that's the case, you can try:
var elemString = // whatever your str is
var id = (elemString.match(/id="([^"]+)"/) || [])[0];
This assumes that the id is the first attribute in the string, as well as a whole litany of other things that will probably break in production but will work in the absence of a coherent understanding of what you're trying to do.
You can simply use the select element id to retrieve the value of the element.
<select id="Type112" class="GridList" rownumber="0" value="Q1 Only" ><option></option><option value="1" selected="selected">Q1 Only</option><option value="2">Q2 Only</option></select>
You can write the javascript to get the element by id Type112
and so on to get the value:
var s = document.getElementById("Type112");
var selNum = s.options[s.selectedIndex].value;
alert(selNum);
Here's a jsfiddle example
Try this.
var list = document.getElementById("Type112");
console.log(list.value)
<select id="Type112" class="GridList" rownumber="0" value="Q1 Only" ><option></option><option value="1" selected="selected">Q1 Only</option><option value="2">Q2 Only</option></select>

document.getElementByName()[0] undefined

This is my js function
function toggleCountry(country)
{
var elem = document.getElementsByName(country)[0].value;
alert(elem);
}
Its being called onclick event
<div class="navBarItems">USA</div>
I have another div with the attribute name="usa" and I want to search for it and disable the text. However, I always get undefined as it returns in my alert.
Edit: Its a div tag.
document.getElementsByName(name) requires that you make use of the name="" attribute.
With that in place, try changing:
var elem = document.getElementsByName(country)[0].value;
To:
var elem = document.getElementsByName(country)[0].innerHTML;
(provided this is your goal)
.value is the wrong method here (there's no value attribute on your element). I was able to access the .innerHTML just fine, so your function is selecting the appropriate element. If .innerHTML is not what you want, you can substitute that for another method. I'm not entirely sure what you're reaching for here, but hopefully this jsfiddle helps:
http://jsfiddle.net/S68qr/
I am not sure of your implementation and Stuart Kershaw already provided a great solution.
Another approach would be to change your HTML to provide a more dynamic selection.
<select onchange="toggleCountry(this.value)">
<option value="USA">USA</option>
<option value="CDN">CDN</option>
</select>
And you can use this function to retrieve the value.
function toggleCountry(country)
{
alert(country);
}
http://jsfiddle.net/LzubU/

jQuery .val() does not work on html chunk?

I cant figure out, why this code does not work as expected:
var $obj = jQuery('<div>xx<input type="text" value="" />xx</div>');
$obj.find('input').val('testing');
console.log($obj.html());
The resulting output is without any change - i.e. no change in value. But append() and other functions works fine. What could be wrong?
value is an atrribute of the input dialog.
Doing .val(...) changes the value property and not the value in the DOM.
See here for the differences between properties and attributes.
If you wanted to see a physical change in the value attribute you could do something like this:
var $obj = jQuery('<div>xx<input type="text" value="" />xx</div>');
$obj.find('input').attr('value','testing');
console.log($obj.html());
Demo: http://jsfiddle.net/maniator/YsZLt/
The "value"-attribute maps to .defaultValue property.
There is no attribute that maps to .value property. However, on non-dirty inputs
inputs, you can set the attribute "value" (and obviously, .defaultValue) and that will be reflected
in the property .value.
Since your input is non-dirty, you can do this
var $obj = jQuery('<div>xx<input type="text" value="" />xx</div>');
$obj.find('input').prop('defaultValue', 'testing');
console.log($obj.html());
//xx<input type="text" value="testing">xx

Identify Hidden Form Value Without an ID or Class

I am writing a Greasemonkey script and I need to be able to take the value from a hidden form element and set it to a variable.
The hidden form value looks like this:
<input type="hidden" name="ASIN" value="B009MO89Y4" />
I have no ID, class, or any way I can see to set the "value" to a variable. This needs to work dynamically and I currently have no way to establish a class or ID to this value.
Is there a Javascript (or jQuery) method to set this?
In other words:
Find "input" with name "ASIN" and set .val() to a variable?
This selector and assignment:
$("input[name='ASIN']").val(); <---- returns value of that input
var inputVal = $("input[name='ASIN']").val(); <-- Assigns it
var temp = "Stuff";
$("input[name='ASIN']").val(temp); <----Assigns the value of the temp var.
You can use the jQuery attribute equals selector
$('input[name="ASIN"]').val(foo);
You can select it via. name in jQuery like so:
var bar = "Example"; // Example text, to be used in val().
var x = $('input[name="ASIN"]').val(bar);
// Sets the variable x to be the value bar for the input with the name ASIN.
Here's a working jQuery jsFiddle.
In pure Javascript *:
var bar = "Example";
document.getElementsByName("ASIN")[0].value = bar;
Here's a working Javascript jsFiddle.
*Please note that although document.getElementsByName is supported well in Firefox, Chrome and Safari, it has limited browser support. in IE and Opera.
Like this:
$('input[name="ASIN"]').val();
Var:
var hiddenAsin = $('input[name="ASIN"]').val();
You can filter your selection with any attribute.
$('input[name=ASIN]').val("New Value")
You can use selector that targets inputs of type hidden. It should look like that:
$('input[type=hidden]');
or simpler:
$(':hidden');
Use this method
var inputs = document.getElementsByTagName('input');
for(var i = 0...)
{
//go through each input and look for the name "ANSI" and the type is hidden.
//and do your changes.
}
this is for javascript remember.
with this you should be able to get that specific hidden form without an ID nor a Class assigned to that specific form.
For pure javascript:
Try document.getElementsByName('name').
Note that cmptrgeekken pointed out that this has limited browser-support (although that would not be an issue with greasemonkey in FF).
As an alternative, if that hidden element has a fixed place you could also access it by index-number in a predictable collection that you got from knownParent.getElementsByTagName('tag')[#] (So the first hidden inputtag inside a form would be number 0).
Another variation is to get (again) knownParent.getElementsByTagName('tag') and loop over that collection to see what element has the 'name' attribute set that you seek.
Simply do:
var target=knownParent.getElementsByTagName('input'), L=target.length;
while(L--){ if(target[L].name==='name'){target=target[L]; break;} }
alert(target.value); //target is now the element you seek.
Example fiddle here.
Good luck!

Categories