How to rewrite text of an option in Javascript? - 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>

Related

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>

Select onChange preview svg

I have little html experience and no java experience and am trying to display an SVG image once the option is selected. Currently the code is at this, which displays a gif image:
<SELECT NAME=SIGN_NFPA onchange=\"
this.form.SIGN_PIC1.selectedIndex = 0;
var id = this.options[this.selectedIndex].value
var lnk = (id) ? 'SignNFPA/'+id+'.gif' : 'images/blank.gif';
window.document.SIGN_PIC1.src = lnk;
return true;
\">
Now we are generating files and want to replace that with this line of code
<SELECT NAME=SIGN_NFPA onchange='$("img[name=SIGN_PIC1]").prop('src',"SignNFPA?nfpa="+this.value);'>
but I keep getting a syntax error, what am I doing wrong? I know it should be a function in onchange but my coworker says you can input code directly instead. Thanks.
Your immediate problem is nested single-quotes around "src". This is causing it to see onchange='$("img[name=SIGN_PIC1]").prop(' as a complete attribute, followed by garbage.
Change those to be a compatible set of quotes:
<SELECT NAME=SIGN_NFPA onchange='$("img[name=SIGN_PIC1]").prop("src","SignNFPA?nfpa="+this.value);'>
but this would read as more "standard" like this:
<SELECT NAME="SIGN_NFPA" onchange="$('img[name=SIGN_PIC1]').prop('src','SignNFPA?nfpa='+this.value);">
But as your are using jQuery, I would strongly suggest moving to using a jQuery event handler, and appropriate data- attributes and not use a inline handler.
e.g. something like the following (not checked for errors - just a guide)
HTML:
<SELECT NAME="SIGN_NFPA" \>
jQuery
$(function(){
$('[name="SIGN_NFPA"]').change(function(e){
var $signpic1 = $('[name="SIGN_PIC1"]')
$signpic1.val(0);
var id = $(this).val();
var lnk = (id) ? 'SignNFPA/'+id+'.gif' : 'images/blank.gif';
$signpic1.attr("src", lnk);
});
});
Use quotes when adding attributes in HTML. Specially in value
<select name="SIGN_NFPA">
<!--options-->
</select>
Using event Handler in jquery
$(document).ready(function() {
$("select[name='SIGN_NFPA']").change(function() {
$('img[name=SIGN_PIC1]').prop('src', 'SignNFPA?nfpa=' + this.value);
})
});
Turned out it was because I was in quote hell, probably should've mentioned that but I'm relatively new to programming. I'm in a perl file using html thats using jquery and the $ sign was being interpreted as a scalar, causing a syntax error. Also simultaneously in quote hell

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/

Using jQuery to pull info from a dropdown and creating a div with that info

I am running an AB split test that will modify a set of dropdown options for shipping options and creating four div containers with the shipping information inside them. The containers will be side by side boxes that are selectable using a button. I am unable to modify the original html. I need to create this by modifying javaScript and an internal stylesheet.
Here is the html I have to work with:
<div id="carrierCommonDiv">
<div class="nc_shipping_price_desc">Prices below reflect <span urlPath="/checkout/shipping_policy_popup.jsp?policy=shipping" relativeObj="shippingChargePopup" class="shippingLink3 popLink checkout_popLink">shipping charges</span> for your order.</div>
<div class="nc_shipping_carrier_select">
<select id="carrierCode" name="carrierCode">
<option value="UG" shippingTotal="$13.95" selected="selected" desc="">Standard Ground ( $13.95 )</option>
<option value="UTS" shippingTotal="$22.45" desc="">Third Day Ground ( $22.45 )</option>
<option value="US" shippingTotal="$27.45" desc="">Second Day Air ( $27.45 )</option>
<option value="UNN" shippingTotal="$37.25" desc="">Next Day ( $37.25 )</option>
</select>
</div>
Thoughts on how to solve this?
It currently looks like this: http://jsfiddle.net/kBws6/ and should look about like this when completed: http://jsfiddle.net/mMqpG/
This should get you started in jQuery.
Demo in jsFiddle
First, find the select element and save it. Loop through each of it's children. In each loop, you can use $(this) to access all the information you'd need from each option and build some html. Insert it after the select element, and finally hide the original select element:
var $select = $("#carrierCode");
$select.children("option").each(function() {
var box = "<div class='shipOption' >"+$(this).text()+"</div>";
$select.after(box);
});
$select.hide();
To add any CSS rules, you should specify the text and then append to the head element. Here's an example of how to do everything in-line, but preferably, you'd create a .css file and link directly to that.
//TEST
$("head").append("<style type='text/css'>"+
".shipOption {"+
"height:150px;"+
"width:100px;"+
"display:inline-block;"+
"border:solid 1px #333;"+
"text-align:center;"+
"float: left;"+
"}"+
"</style>");
//PROD
$("head").append("<link rel='stylesheet' type='text/css' href='mystyle.css'>");
For click event handling, after you've modified the dom, just setup a listener for click events on anything with the shipOption class:
$(".shipOption").click(function() {
alert("You clicked "+$(this).attr("value"));
});
Ok, here's a start.
JS Fiddle Example
If I'm reading your post correctly, it looks like you want to change how all the html displays without actually modifying the html.
Here's is a simple fiddle to show a method of adding/ removing those elements. All I'm doing is using a forEach function to iterate over a sliced array of the option elems and make new div elems, and then I use event delegation to listen for clicks to those new divs. I used vanilla JS - you don't really need to use jQuery for this kind of thing, but if you want to it's pretty much the same idea (just using $ selectors and $(foo).on('click'... instead).
The display isn't perfect, so you will want to mess around with that, but it should get you going.

Javascript getElementById()

I'm trying to create a generic javascript function that would change attributes on events.
The way it would work is
function fooFunction(sourceElement)
{
var newName = sourceElement+'Span';
var newElement = document.getElementById(newName);
//Important line
newElement.property = "enter properties here";
}
and I'd call it with something like
<img src="foo.gif" id="foo" name="foo" onmouseover="fooFunction(this.id);"/>
<span id="fooSpan" name="fooSpan">some text here</span>
So in theory, when hovering the image, it should change whatever propery I need to change on the fooSpan object. It works in Opera, but on IE it returns a null object.
Any ideas ?
The idea would be that I would have multiple images that would automatically trigger the property change on the associated text span (typically the css style).
Are you sure you're getting the ID properly in IE? Maybe the ID being passed in is null in IE (perhaps this.id isn't working?).
Try calling it like this:
<img src="foo.gif" id="foo" name="foo" onmouseover="fooFunction('foo');"/>
and see if that helps. I don't see any reason why getElementById() would fail, so the only thing I can think of is that it's an ID issue.
May be this line won't work in IE. "newElement.property"
I don't know the exact reason.
You can use this instead of that line
newElement.setAttribute(property,"enter properties here");
In the mean time, i am trying to find out the reason behind the error.
My suggestion would to do something like this.
function fooFunction(sourceElement,property,propertyValue) {
var newElement = document.getElementById(sourceElement);
newElement.setAttribute(property,propertyValue);
};
And your HTML would look like:
<img src="foo.gif" id="foo" name="foo"
onmouseover="fooFunction('fooSpan','class','mouseover_span');"/>
<span id="fooSpan" name="fooSpan">some text here</span>
I'd STRONGLY urge you to consider using jQuery's built-in attr() method which integrates the function you want perfectly across browsers and is incredibly easy to use.
Using your example, if you wanted to change the "src" property for "foo", you could do it in a single line of code:
$("#foo").attr("src","images/whatever.png");
Similarly, if you wanted to change the html WITHIN "fooSpan", all you'd have to do is:
$("#fooSpan").html("something else");
You can even tie these to events that are going to give you a lot more flexibility than the onmouseover property:
$(document).ready(function(){
$("#foo").mouseover(function(){
$("#fooSpan").html("something else");
$("#foo").attr("src","images/whatever.png");
});
});

Categories