document.getElementByName()[0] undefined - javascript

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/

Related

How to rewrite text of an option in Javascript?

I've encountered one issue: I don't know how to rewrite the (inner)text of an option in a select.
My goal would be something like that:
<select id="example-dropdown">
<option id="option-id" value="example-option">Example</option>
</select>
<button id="change-option-text-btn" onclick="document.querySelector('#option-id').innerText = 'Example 2'">Click Me</button>
I know this is a possible duplicate, but all of the answers I found are not working for me (I also found some jQuery ones, I don't know if they don't work neither), such as:
document.querySelector("#example-dropdown").options[0].text = "Example 2"
Didn't encounter any error messages.
Edit: Ok, I'm sorry, I didn't say it: this is just an example code, the onclick is there just for saving time
Well, there are a couple of issues with your current code and I will point them out briefly here.
First of all, it is better to stick with unobtrusive solution in your code and handle all of the logic inside a <script> or JS file instead of handling them in the HTML itself. So for this, I just removed the onclick handler from the HTML and moved it in the JS section and tried to access the element and adding event to it by addEventListener approach.
Your first snippet should work as expected if you select the right element in the query selector, so you can change the selector to document.querySelector('#example-dropdown option[value=example-option]'), but due to the innerText drawbacks (Which you can find here) it is better to not use it at all for changing the inner text of elements.
If you do not want to use innerText for its drawbacks, to change the content of the HTML tag you can use the innerHTML or textContent property. Which is in your case since you are only trying to change the text of the option alone you need to use textContent.
Your final code should be something like this:
const btn = document.querySelector('#change-option-text-btn');
const select = document.querySelector('#example-dropdown');
btn.addEventListener('click', function() {
select.options[0].textContent = 'Example 2'
});
<select id="example-dropdown">
<option value="example-option">Example</option>
</select>
<button id="change-option-text-btn">Click Me</button>
Also, in your particular case since you are trying to change the inner text of the select option there is one more option for you as you tried earlier is to use text property which works the same as textContent and it is only available for HTMLOptionElements.
So, document.querySelector("#example-dropdown").options[0].text should do the work for you.
And it will be like this:
const btn = document.querySelector('#change-option-text-btn');
const select = document.querySelector('#example-dropdown');
btn.addEventListener('click', function() {
select.options[0].text = 'Example 2'
});
<select id="example-dropdown">
<option value="example-option">Example</option>
</select>
<button id="change-option-text-btn">Click Me</button>

Uncaught TypeError: Cannot read property 'append' of null in jQuery

Starting from this jQuery code:
var country_name_list=document.getElementById("country");
$.post(getcountry,function (data) {
var Rcountry_name_list=JSON.parse(data);
var arr=[];
for(var i=0;i<Rcountry_name_list.countries.length;i++){
var r_id=Rcountry_name_list.countries[i].country_id;
var r_name= Rcountry_name_list.countries[i].country_name;
var option_name = document.createElement("option");
option_name.textContent =r_name;
option_name.value = r_id;
country_name_list.append(option_name);
}
});
HTML
<form method="post" action="" id="rform" novalidate="novalidate">
<label class="control-label">Country </label>
<select id="country" name="country" class="form-control" >
<option value=" " disabled selected hidden>Select Country</option>
<option value="0"></option>
</select>
</form>
On the line country_name_list.append(option_name); I get the following error
Uncaught TypeError: Cannot read property 'append' of null in jQuery
First of all, when a DOM selector returns null, it means the element was not found. So you have to wait for the DOM to be loaded.
With jQuery it's enough to wrap your selector in the following statement
$(document).ready(function(){
});
vi5ion's right, but you could also improve your code
var country_name_list = document.getElementById("country");
Here you didn't use jQuery, so you have to keep using javascript DOM methods.
$.get(getcountry, function (data) {
Here $.get is enough
var response = JSON.parse(data);
I think Capital letter is only for classes
var option, current;
If you create the variables here, you avoid creating a new variable for each loop, so will save time!
var list = response.countries;
for(var i=0; i < list.length; i++){
current = list.countries[i];
option = document.createElement("option");
option.textContent = current.country_name;
option.value = current.country_id;
country_name_list.appendChild(option_name);
As vi5ion suggests appendChild() is what you need
}
});
It seems easier to read the code now, didn't it?
Hope this is useful!
country_name_list is not a jQuery object and therefore doesn't have the append() function.
In fact, most of your code is plain JavaScript and not jQuery, so you would probably want to use the function appendChild() instead.
Edit: added alternative jQuery solution below
If you insist on using jQuery you could wrap your variable.
That can either be done here
var country_name_list = $('#country');
or here
$(country_name_list).append(option_name);
but not both.
When you receive an error of type "Cannot read property XXX of null", you want to make sure that your element exists when your script is called.
For instance, you would place your javascript right before the closing tag to make sure that the element has is in the DOM.
Alternatively, if you have your script inserted in the header, or prior in the page, you may want to enclose i inside the $.ready() method to ensure that it is only run after the DOM is ready
$( document ).ready(function() {
... your code
}
You can find more information at: https://api.jquery.com/ready/
I faced a similar issue, I did try the above solutions, but mine was due to different reason.
Therefore, one solution would be wrapping it under the document.ready
$(document).ready(function(){
});
One another solution will be, try using jQuery() instead of $(), this was helpful for me.
jQuery('#item_field').append('<div></div>');
instead of
$('#item_field').append('<div></div>');
I got the same error
I tried entering the script tag in the body section
It worked for me

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>

Undefined option name 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;

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