JavaScript changing HTML code after loading in a div - javascript

I have a page that gets values from a DB, I can't control the values / how they are called, but the end result looks like standard HTML code, for example:
<div id="myDiv" class="controls">
<select id="jform_province" name="jform[province]">
<option value="AB">Alberta</option>
<option value="BC">British Columbia</option>
<option value="MB">Manitoba</option>
</select>
</div>
I'm looking to put a script at the end of the page that can modify the option elements by say adding a function so it looks like this:
<option value="AB" onClick="someFunction()">Alberta</option>
How can I modify the code? I know how to edit the entire content of the div but I want to change the elements, I will not know what the values of the elements are so the script needs to find all option tags in "myDiv" (I have other lists on the page I don't want changed) and add that code to all of them.
Thanks

Just attach an event handler:
document.getElementById('jform_province').onchange = function() {
switch(this.options[this.selectedIndex].value) {
case "AB": someFunction(); break;
// define other cases as needed
}
};
Note that <option> elements do not fire onclick events when selected, and even if they did it wouldn't detect alternate input methods such as using the keyboard. The code above provides an alternative.

Related

How to select a dropdown element on a website using javascript code?

I am writting a javascript program that needs to be able to select an element on a dropdown and then continue browsing. My problem is that even though I can select a dropdown element and that I can see the dropdown change on the website, the element I have selected doesn't seem to be "registered" and when I continue my browsing, the dropdown is back to the default option.
I figured out that maybe the website needs a mouse click to register the change so I have tried clicking on the dorpdown after selecting the right option but it still doesn't work.
Here is the different codes I have tried and which seems to both have the same problem :
//first try:
document.getElementById('SingleOptionSelector-0').selectedIndex = 2;
//second try :
document.getElementById('SingleOptionSelector-0').value = '3';
I tried to click on the dropdown menu like this:
document.getElementById('SingleOptionSelector-0').click();
But it doesn't expand. It's like the click is not registered which seems very strange to me because when I click somewhere else on the web-page it works just fine
I have seen a lot of questions about how to interact with a dropdown menu,but no one else seems to have the problem that when you change the value it is not registered by the web-page
The relevant HTML is below:
<select class="single-option-selector single-option-selector-product-template_original product-form__input" id="SingleOptionSelector-0" data-index="option1">
<option value="1">Hamburger</option>
<option value=" 2">fries</option>
<option value="3">Coke</option>
<option value="4">Diet Coke</option>
</select>
edit : It seems that I was not clear enough. An example of my problem is the website https://www.xhibition.co/collections/air-jordan/products/jordan-23-engineered-full-zip-jacket?variant=29510378848328 . When I use one of these methods to change the "size" dropdown, I can see it changing but when going to the basket, the size of the element I just added is the default one ('M'). That's what I mean by the website "not registering" the dropdown change.
Try this.
document.getElementById('myDropDown').value = "2"
Your question is kind of vague, but I think the sample below should give you a good idea of how to get and set select element values and also how to use addEventListener to know when a change event has taken place:
const selectEl0 = document.querySelector('#SingleOptionSelector-0');
const selectEl1 = document.querySelector('#SingleOptionSelector-1');
const onChange = e => selectEl1.value = e.target.value;
selectEl0.addEventListener('change', onChange)
The second select element will update it's value when the first one changes:<br/>
<select class="single-option-selector single-option-selector-product-template_original product-form__input" id="SingleOptionSelector-0" data-index="option1">
<option value="1">Hamburger</option>
<option value="2">fries</option>
<option value="3">Coke</option>
<option value="4">Diet Coke</option>
</select>
<select class="single-option-selector single-option-selector-product-template_original product-form__input" id="SingleOptionSelector-1" data-index="option1">
<option value="1">Hamburger</option>
<option value="2">fries</option>
<option value="3">Coke</option>
<option value="4">Diet Coke</option>
</select>

Selected attribute of select options is not updating automatically

I have multiple selects on my page, each has multiple options.
However, If I select an option then the attribute selected of the option is not updating. Shouldn't this happen automatically?!
Example:
<select id="browsers">
<option value="Firefox">Bing</option>
<option value="InternetExplorer" selected="selected">Internet Explorer</option>
<option value="Chrome">Chrome</option>
</select>
By inspecting the DOM with the developer console, you should see, that the selected attribute is not changing even after selecting another option.
However I found a workaround. To solve this issue we can use this code:
$(document).on("change","select",function() {
$("option[value=" + this.value + "]", this)
.attr("selected", true).siblings()
.removeAttr("selected")
});
Example:
$(document).on("change","select",function() {
$("option[value=" + this.value + "]", this)
.attr("selected", true).siblings()
.removeAttr("selected")
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="browsers">
<option value="Firefox">Bing</option>
<option value="InternetExplorer" selected="selected">Internet Explorer</option>
<option value="Chrome">Chrome</option>
</select>
This works kind of. However, If I select another option than the default option, e.g. Chrome and reload the page, then the option Chrome is still selected even after reload, BUT the selected attribute still points to Internet Explorer!
Which is the best approach to solve this?
My idea is to run through all selects on $(document).ready() and select the option where the selected attribute points to.
But why does this all not happen automatically?
Is it a bug or a feature?
The selected attribute defines if an element should be selected on pageload. If you post a form with a select element, the chosen option will be the one posted, regardless of the initial selected element.
What do you need the selected-attribute for in your case?
Edit: Based on your comments I made a fiddle
Fiddle 1 https://jsfiddle.net/q3fpafov/1 selects like you want
Fiddle 2 https://jsfiddle.net/bge9bsa7/2/ only files available for a chosen language are shown
I hope it's somewhere along the lines of what you're looking for.
The reason for your option still being selected when you reload is browser based. But the selected-attribute does nothing for the usability of the option. Also, it won't change because you don't change the way the HTML-element itself is being rendered (at page load)
Note: selected="selected" is not necessary, simply selected attribute will work as well.
When present, select attribute specifies that an option in select should be pre-selected when the page loads.
Also, the pre-selected option will be displayed first in the drop-down list.
Those 2 should be only effects of the selected attribute.
Note the keywords - when the page loads. He is either there or not when a browser loads the page.
If you wanna make it dynamic you need to use JavaScript. What do you wanna achieve with this? Having attribute selected on the correct element when reloading page or programmatically select the correct element after the page has been loaded?
If you simply wanna make element selected there is easier way trough either value:
jQuery("#browsers[value='the value of the one you like']").attr('selected','selected');
Or by index (mind, indexes start at 0 not 1):
document.getElementById("browsers").selectedIndex = "2";
The problem before was, that after selecting an option and reloading the page, the option was remembered during page reload, even though the attribute selected pointed to another option.
I solved it by calling the function below everytime. The function finds out which is the truly selected option, even after page reload.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="downloadSelect" id="select_179">
<option value="-">Please select</option>
<option value="link_2748" selected="selected">Deutsch</option>
<option value="link_2749">Chinese</option>
</select>
<button onclick="return showSelectedOption('select_179');">Show Option Text</button>
<script>
function showSelectedOption(pSelectID)
{
var text;
$("#"+pSelectID)
.find("option")
.each(function(){
if ($(this).prop("selected")) {
text = $(this).text();
}
});
console.log(text);
}
</script>
You can check the value of the select when it changes to see what it has been changed to.
var select = document.getElementById('browsers');
select.addEventListener('change', function(e) {
localStorage.setItem('browser', this.value);
});
var browser = localStorage.getItem('browser');
if (browser) {
select.value = browser;
}
<select id="browsers">
<option value="Firefox">Firefox</option>
<option value="InternetExplorer" selected="selected">Internet Explorer</option>
<option value="Chrome">Chrome</option>
</select>
edit
So, I missed the part about storing the value so that it persists when the page is reloaded, and depending on the OP's use case, I would suggest using localStorage to save the value when it is changed, and to read from it when the page is reloaded.
I have edited the snippet to reflect this (code is simplified)

Using a ONE WORD javascript variable in form field VALUES

I have a function that gets values from a the URL and then posts it to various places on the page.
I can't figure out how to get the values to read inside form field values.
<OPTION Value="<script type="text/javascript">document.write(Position)
</script> has final say">
I know I can't do that specifically, but I've tried various configurations and nothing posts the variable inside the value field.
The document.write function is working on the plain html, I have tested that. I just don't know to make it read inside a form field value and display the results properly.
How do I get one word to display as a variable, without having to create a function that inputs the value of each field. There are way too many fields to make that viable - this needs to populate into maybe 200 or 300 variables, so I really need it to be the word.
The site is standalone so I can't use php as I understand it. If there's a way I'm open to it. I did try the php echo to call the field name but I don't know enough about php to know if I'm missing something.
I am open to solutions where I can upload files into the standalone site though.
Thanks in advance.
Is this what you're looking for?
var position = 'helloworld'
document.getElementById('id1').options[0].value=position;
<select id="id1">
<option>The Value is the POSITION variable.</option>
</select>
I added an ID to the select box (<select id="id1">). Then you can use the script to insert the position variable as the value of the options within the select.
If this is not what you're looking for then you really need to update your question with more sample from your code (i.e some HTML would be nice).
If you are stuck writing code only on the client-side, then you may want to use a client-side library like jQuery to help you manage your DOM manipulation.
For example, you can set a class for every variable you want to set and then use jQuery to replace the contents of those elements.
var values = {
position: "top",
name: "steve"
}
$(".position").text(values.position).val(values.position)
$(".name").text(values.name).val(values.name)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option class="position"></option>
<option class="name"></option>
</select>
<select>
<option class="name"></option>
</select>
<select>
<option class="position"></option>
</select>
<select>
<option class="position"></option>
<option class="name"></option>
<option class="position"></option>
<option class="name"></option>
</select>

Catch attribute change on automatically changed elements

I want to create two selections on my webpage which will be connected to each other so that both selections will always be the same. Let me explain in a mock example:
I have a webpage with two selects:
<select class="myselector">
<option value='1'>1
<br>
</option>
<option value='2'>2
<br>
</option>
</select>
<select class="myselector">
<option value='1'>1
<br>
</option>
<option value='2'>2
<br>
</option>
</select>
Note: in reality, I have more than just the two selects and I want them all to be connected.
Now, I want the webpage to automatically set the second selector to the value of the first if the first is changed. I also want to perform some other things on the select that has changed, so I also want the change event to trigger on the other selector. My first thought was simply to do this:
function valChange() {
myfun();
$('.myselector').val($(this).val());
}
$('.myselector').on('change', valChange);
This does what I need in that it changes the selected values so they match
This does not trigger the change event in the other select, so myfun runs only once
My next thought was to add $('.myselector').change(); to the end of the valChange function, but this (naturally) causes an infinite loop of change events.
My question is, therefore:
How can I trigger the change event in only the elements that have been
changed automatically (not by a user)?
I think it could be done by having both the change and the click event, but that just seems wrong and ugly to me.
EDIT: I found a way to solve my problem through the use of jquery selectors. If there exists a more elegant way of solving the problem, I will still be happy to see it though.
function valChange() {
myfun()
var others = $('.myselector[value!=' + $(this).val() + ']');
others.val($(this).val());
others.change();
}
$('.myselector').on('change', valChange);
JSfiddle for my solution:
http://jsfiddle.net/5xum/svjbdxgs/
you can use each method of jquery
function valChange() {
var _this = $(this)
$('.myselector').each(function(){
myFun();
$(this).val(_this.val());
});
}
$('.myselector').on('change', valChange);
here is fiddle for the same fiddle link

Click already selected option in select box

This seems like it should be easy, but the limitations of the <select> object are rather irritating. I have a select box with four options, and when you navigate to a page, the option is set to the page you are on. I want to make it so that the user can refresh the page by selecting the same option - that is, selecting the option that's already selected.
Unfortunately, the onclick event doesn't work across browsers. Most people recommend using onchange, but that doesn't work in the case I'm talking about. The approach I've been taking is to add an extra item at the top that holds what's currently selected and does nothing when clicked on, and then switch to that option after firing the onchange event, so that when the user re-selects the option they're actually changing. That's awkward though, because in the drop-down there are two of the same item, and I shouldn't have to do it.
What is a good cross-browser way to solve this problem? Something not terribly complicated and something in regular JavaScript would be preferable.
This might help:
function onFocus(element){
element.setAttribute('old-value',element.value);
element.value='';
console.log('reset');
}
function onBlur(element){
if(element.value=='')
element.value = element.getAttribute('old-value');
element.removeAttribute('old-value');
}
function onChange(element){
console.log('New Value : '+ element.value);
}
<select id="mySelect" onfocus="onFocus(this)" onchange="onChange(this)" onblur="onBlur(this);">
<option value="" style="display:none;"></option>
<option value="one">one</option>
<option value="two">two</option>
<option value="three">three</option>
</select>
Here you go with the solution
$("select[id=mySelect] option").click(function(){
alert("HI");
});
This will alert -HI- everytime a click is made on an option. The change has also been made in the select box and event is also been performed.

Categories

Resources