Changing Selected Option in a Drop Down Menu in Javascript - javascript

I have this code and I want to change the selected item,being Million(s), to something other than that. How would I do this?
<td>
<select name='list_" + i + "' id='list'>
<option value='0'>Trillion(s)</option>
<option value='1' selected='selected'>Billion(s)</option>
<option value='2'>Million(s)</option>
<option value = '3'>Below One Million</option>
</select>
</td>
Here is the lines of code im using to try to change the selected option
for (var key in myObject) {
if (myObject.hasOwnProperty(key)) {
if(document.getElementById("list_"+counter).innerHTML=="true"){
document.getElementById("c" + counter).value = myObject[key];
counter++;
}else{
if(myObject[key]>=1.0E12){
myObject[key]=myObject[key]/1.0E12;
//document.getElementById("list").value=counter;
//document.getElementById("list").getElementsbyTagName('option')[counter].value=counter;
counter++;
}
document.getElementById("c" + counter).value = myObject[key];
}
}
}

I may have understood your requirement wrong.
If you want to change the selected item then it is just matter of changing "selected" attribute.
Let say I want to change it to Trillion, then this is how the code will look like:
<select name='list_" + i + "' id='list'>
<option value='0' selected='selected'>Trillion(s)</option>
<option value='1' >Billion(s)</option>
<option value='2'>Million(s)</option>
<option value = '3'>Below One Million</option>
</select>
Now let say you want to change the selected item through pure javascript(NO JQUERY)
Here is full example, the selected item will change when you click button.
Note: It is just a matter of changing the index.
<head>
<title> Changing selected option in drop-down menu in JS</title>
<script type="text/javascript">
function changeSelected(){
document.getElementById("list").selectedIndex = 1;
};
</script>
</head>
<body>
<p> Test string....</p>
<td>
<select name='list_" + i + "' id='list'>
<option value='0' selected='selected'>Trillion(s)</option>
<option value='1' >Billion(s)</option>
<option value='2'>Million(s)</option>
<option value = '3'>Below One Million</option>
</select>
<button onclick="changeSelected()">Try It</button>
</td>
</body>

Related

How can I get the latest HTML tags of a changeable elements, like Select, Checkbox, Input in JS/Jquery?

I need to get the HTML tags of the changeable element so that I can pass them to create a PDF. But, whenever I use element.innerHTML or element.html(), I get the HTML tags generated after page load but not after I made the changes.
In HTML:
<select id="testSelect">
<option id="no">-- not selected --</option>
<option id="one" selected>1</option>
<option id="two">2</option>
</select>
In JS:document.getElementById("testSelect").innerHTML
It returns:
"
<option id="no">-- not selected --</option>
<option id="one" selected="">1</option>
<option id="two">2</option>
"
And now if I manually change the value to 2, then
In JS:
document.getElementById("testSelect").value
"2"
as you can see the value is changed. But, the HTML tags won't change as
In JS:
document.getElementById("testSelect").innerHTML
"
<option id="no">-- not selected --</option>
<option id="one" selected="">1</option>
<option id="two">2</option>
"
Still, I get the old tags. Instead, I want something like this.
"
<option id="no">-- not selected --</option>
<option id="one">1</option>
<option id="two" selected="">2</option>
"
I made this script for you hope it helps you!
var selectBox=document.querySelector("#testSelect");
selectBox.addEventListener("change", function(){
const selectBoxOptions=selectBox.querySelectorAll("option");
selectBoxOptions.forEach((option)=>{
option.removeAttribute("selected");
});
detectOptionObjectByValue(this, this.value).setAttribute("selected", "selected");
});
function detectOptionObjectByValue(selectBox, value){
const options=selectBox.querySelectorAll("option");
let pos=0, obj=false;
options.forEach(function(option){
option.value==value?obj=options[pos]:0;
pos++;
});
return obj;
}
<select id="testSelect">
<option id="no">-- not selected --</option>
<option id="one" selected>1</option>
<option id="two">2</option>
</select>
You can make a function which will iterate through all options and set all the selected attributes to false
$('select option[value=' + i + ']').attr("selected",false);
Then based on the value selected set the attribute to true
$('select option[value=' + this.value + ']').attr("selected",true);
const dropdownElement = document.getElementById('testSelect')
dropdownElement.onchange = function () {
clearSelected()
$('select option[value=' + this.value + ']').attr("selected",true);
console.log("value selected: " + this.value);
console.log("html: " + dropdownElement.innerHTML)
};
// set all the options to unselected
function clearSelected(){
var elements = dropdownElement.options;
for(var i = 0; i < elements.length; i++){
$('select option[value=' + i + ']').attr("selected",false);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="testSelect">
<option id="no" value="0">-- not selected --</option>
<option id="one" value="1" selected>1</option>
<option id="two" value="2">2</option>
</select>
On jQuery site you have similar question explained:
https://learn.jquery.com/using-jquery-core/faq/how-do-i-get-the-text-value-of-a-selected-option/
$(function(){
$('#select').change(function(){
$('#output-value').text($(this).val());//get value
$('#output-element').text($(this).find('option:selected').text());//get text of selected element
$(this).find('option').each(function(){
$(this).attr('selected', $(this).is('option:selected')); //adds and removes selected attribute
});
$('#output-html').text($(this).html());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="select" >
<option>--</option>
<option value="1" >1 val</option>
<option value="2" >2 val</option>
<option value="3" >3 val</option>
</select>
<br/>
Value
<div id="output-value" ></div>
Element
<div id="output-element" ></div>
HTML
<div id="output-html"></div>

Getting the value of a dropdown menu using jQuery

I have added a little drop down menu to a webpage:
function addDropDownMenu() {
var positionMenu = $(
"<form class='drop_down_menu'>" +
"<select name='roles'>" +
"<option value='notSelected'>Not Selected</option>"+
"<option value='relevant'>Relevant</option>"+
"<option value='notRelevant'>Not Relevant</option>" +
"</select>" +
"</form>");
$('#profile-experience .position').prepend(positionMenu)
}
I am trying to get the value of either Relevant or Not Relevant.
However, when I run this code I keep getting an empty string.
var x = $('.drop_down_menu')[0]
// x is the form
$(x).val()
returns ""
What am I missing? Doing wrong?
You could try this:
var selectedValue = $('.drop_down_menu>select').val();
var selectedValue = $('.drop_down_menu>select').val();
console.log('The selected value is: '+ selectedValue);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class='drop_down_menu'>
<select name='roles'>
<option value='notSelected'>Not Selected</option>
<option value='relevant' selected>Relevant</option>
<option value='notRelevant'>Not Relevant</option>
</select>
</form>
$('.drop_down_menu') statement returns a jquery element with the properties and methods corresponding to it, but $('.drop_down_menu')[0] just returns the HTML DOM element.
You have to use value property in order to obtain the value of select element.
console.log($('select')[0].value);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name='roles'>
<option value='notSelected'>Not Selected</option>
<option value='relevant' selected>Relevant</option>
<option value='notRelevant'>Not Relevant</option>
</select>
Your example does not work because you have to use a selector for select element
var x = $('.drop_down_menu > select')[0]
console.log($(x).val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class='drop_down_menu'>
<select name='roles'>
<option value='notSelected'>Not Selected</option>
<option value='relevant' selected>Relevant</option>
<option value='notRelevant'>Not Relevant</option>
</select>
</form>
var _val = $("[name='roles']").val();
console.log(_val);

Data list how to get the selected name instead of value

I am using Datalist for showing the autocomplete values of select option.
<input type="text" class="form-control input-sm" name="referralName" id="referralName" list="referralNameList">
<datalist id="referralNameList">
<option value="one">Name 1</option>
<option value="two">Name 2</option>
<option value="three">Name 3</option>
</datalist>
Now using javascript i am able to get the value of selected option, My concern is how can I get the corresponding name, like when I select option "one" I should get the value as "Name 1"
$("#referralName").on('blur',function(){
var value=$("#referralName").val();
console.log("value od selected referral "+value)
});
How to get the selected Names.
You need to get the option based on selected value then you can set text
$("#referralName").on('input', function() {
var value = $(this).val();
//Persist selected value in a hidden input
$('#referralNameValue').val(value);
//For debugging
console.clear();
console.log("value of selected referral " + value)
//update value
if (!!value.length) {
var text = $("#referralNameList option[value=" + value + "]").text();
$(this).val(text);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control input-sm" name="referralName" id="referralName" list="referralNameList">
<input type="hidden" id="referralNameValue" list="referralNameList">
<datalist id="referralNameList">
<option value="one">Name 1</option>
<option value="two">Name 2</option>
<option value="three">Name 3</option>
</datalist>
You can get the text using text() of selected option like this
$(document).ready(function () {
$("#referralName").on('change', function () {
var value = $("#referralName").val();
var text = $("#referralNameList").find('option[value=' + value + ']').text();
console.log("Text of selected referral " + text )
});
});
Easy..
$('#referralName').change(function(e){
var val = e.target.value
console.log($("#referralNameList option[value='" + val + "']").text());
});
Easy and fast solution:
Append data-name attribute in <option> like below
<datalist id="referralNameList">
<option data-name="Name 1" value="one">Name 1</option>
<option data-name="Name 2" value="two">Name 2</option>
<option data-name="Name 3" value="three">Name 3</option>
</datalist>
and then get the selected text using below code
$("#referralNameList :selected").data('name');
which will give you the name, the fastest way.
by the way did you tried
$("#referralNameList :selected").text();

Redirect to a URL with a value at end of the javascript automatically

I am new to javascript and I want a code for wordpress. I have three select options. City, Area and House/flat. Earlier I used same name for two select options and the result was mydomain/s=mycity&s=house but I want it to be like mydomain/?s=firstoptionvalue+secondoptionvalue+thirdoptionvalue
<form method="get" id="searchform">
<select id="text-one">
<option selected value="base">Select City</option>
<option value="city1">city1</option>
<option value="city2">city2</option>
</select>
<select name="a" id="text-two">
<option>Select Your City First</option>
</select>
For second I have used script
$(function() {
$("#text-one").change(function() {
$("#text-two").load("mydomain/textdata/" +
$(this).val() + ".txt");
<h2>Property Type: </h2> <select name="c" id="text-three">
<option value="house">House</option>
<option value="flat">Flats</option>
<option value="plot">Plots</option>
</select>
<input type="submit" id="searchsubmit" value="Search" class="btn2" />
</form>
<span id="s"></span>
Id is coming correctly in span. So I want something like when this javascript ends it automatically redirects to the mydomain/s=(thevalue of s concatinated in javascript)
<script>
$(function() {
$("#text-three").change(function() {
document.getElementById('z').innerText =
document.getElementById('text-one').value + '+' +
document.getElementById('text-two').value + '+'
document.getElementById('text-three').value;
});
});
function myFunction() {
window.open("mydomain/s=z");
}
</script>
I need this url mydomain/?s=firstoptionvalue+secondoptionvalue+thirdoptionva‌​lue . At the end i tried to use mydomains/s=s but it's not working. I know nothing about javascript but the value is coming correctly in span id="s" but i don't want it in span. I want it in window.open("mydomain/s=z");
I am not sure i am understanding your question but i believe this is what you are looking for the snippet below will obviously not load mydomain.com or run the window.open but you can modify those lines for your implementation
$(function() {
$("#text-one").change(function() {
$("#text-two").load("mydomain/textdata/" + $(this).val() + ".txt");
})
$("#text-three").change(function() {
$('#s').text(
$('#text-one').val() +
$('#text-two').val() +
$('#text-three').val())
var theLink = $('#s').text();
console.log(' window.open(mydomain.com/?s='+theLink+')');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="get" id="searchform">
<select id="text-one">
<option selected value="base">Select City</option>
<option value="city1">city1</option>
<option value="city2">city2</option>
</select>
<select name="a" id="text-two">
<option>Select Your City First</option>
</select>
<h2>Property Type: </h2>
<select name="c" id="text-three">
<option value="house">House</option>
<option value="flat">Flats</option>
<option value="plot">Plots</option>
</select>
<input type="submit" id="searchsubmit" value="Search" class="btn2" />
</form>
<span id="s"></span>
window.open(); accepts a string that represents the URL that you want the browser to be directed to.
In this case, window.open("mydomain/s=s"), will redirect to "mydomain/s=s". I'm assuming that when the script is executed that's the URL that you're getting.
With document.getElementById('s').innerText you are setting the contents of the element with id of "s" to the value of "text-one", "text-two", and "text-three".
What you need to do in order to have the page redirect as you would like is either set the value of "text-one", "text-two", and "text-three" to a variable and then use that variable in the URL or use the values directly.
For example:
function myFunction() {
window.open("mydomain/?a=" + document.getElementById('text-one').value + '&b=' + document.getElementById('text-two').value + '&c=' + document.getElementById('text-three').value;
}
OR:
function myFunction() {
var a = document.getElementById('text-one').value;
var b = document.getElementById('text-two').value;
var c = document.getElementById('text-three').value;
window.open("mydomain/?a=" a + '&b=' + b + '&c=' + c);
}
Finally, you need to call myFunction() somewhere, most likely in an on click event.

How to add one row from two drop down list to table and remove when select

I have two drop down list
first for projects
second for employees
I need when select value from first drop down list(projects) then select value from second drop down list (employee)
add new row of selected value from both two drop down list to table as following
suppose i select
one adil
value selected removed from two drop down list both and inserted in table
and when make remove from table added to drop down list
my code as following
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script>
</script>
</head>
<body>
<div>
Project : <select id="myproject">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
</select><br />
Employees : <select id="myemployee">
<option value="1">ahmed</option>
<option value="2">mohamed</option>
<option value="3">saiad</option>
<option value="4">adil</option>
</select>
</div>
<table id="tb">
<tr><td>ProjectName</td><td>EmployeeName</td></tr>
</table>
</body>
</html>
How i do that by jquery
Firstly, since you want to perform the insertion right after selecting the project and employee, to make sure the change event occurs, let's add a dummy option in your two selects first:
<div>
Project : <select id="myproject">
<option value="">---select---</option>
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
</select><br />
Employees : <select id="myemployee">
<option value="">---select---</option>
<option value="1">ahmed</option>
<option value="2">mohamed</option>
<option value="3">saiad</option>
<option value="4">adil</option>
</select>
</div>
If you want to remove the row from table, maybe need another <td> to put the actions, so change the table to:
<table id="tb">
<tr><td>ProjectName</td><td>EmployeeName</td><td>Action</td></tr>
</table>
Then create a JS function to do the insertion:
function removeAndAdd() {
var project = $('#myproject option:selected').detach();
var employee = $('#myemployee option:selected').detach();
var newproject = '<td class="td-project" data-value="' + project.val() + '">' + project.text() + '</td>';
var newemployee = '<td class="td-employee" data-value="' + employee.val() + '">' + employee.text() + '</td><td><button class="btn-remove">Remove</button></td>';
$('#tb').append('<tr>' + newproject + newemployee + '</tr>');
}
this function will fetch the selected value from your dropdown lists and create a new row in the table. Next, bind the function to the change event of your selects:
$('select').on('change', function(e) {
if (($('#myproject').val()) && ($('#myemployee').val())) {
removeAndAdd();
}
});
Finally, when the remove button is click, find the project and employee from the same row, insert them back to the dropdowns, and remove the row from the table:
$('#tb').on('click', '.btn-remove', function(e) {
var row = $(this).closest('tr');
var project = row.find('.td-project');
var employee = row.find('.td-employee');
$('#myproject').append('<option value="' + project.attr('data-value') + '">' + project.text() +'</option>');
$('#myemployee').append('<option value="' + employee.attr('data-value') + '">' + employee.text() +'</option>');
row.remove();
});
The full demo can be found Here

Categories

Resources