Getting the selected option in Javascript/Node.js - javascript

Self teaching Node.js and Javascript stuff. I have in the form in my HTML and select, drop down menu option. How do I get the index of the selected value?
So far im trying this:
var e = req.body.boolean_choice;
boolChoice = e.selectedIndex;
I have the req.body working for getting the inputted values in a text box, but it tells me selectedIndex is not a thing. So then I tried:
var e = req.body.boolean_choice
to see what that gave and it just gave undefined.
Is there a way to do this?
Here is the HTML:
<form action="http://localhost:3000" method="POST">
Form:<br>
<br>
<br>
Text Box 1: <input type="text" name="tb1" size="35" placeholder=""#10SadioMane" OR "#Mane"">
<br>
<br>
<select id="choice" name="choice">
<option value="OR">OR</option>
<option value="AND">AND</option>
</select>
<br>
<br>
<input type="submit" value="Submit">

Form submitting will pass only value property of selection.
Also use debugger in IDE that you use, to explore req.body, instead of trying to guess what's there.

Happy to help.
First of all get the Selected option DOM element
var el = document.querySelector('#choice option:selected');
ibn your case it will be
req.body.querySelector('#choice option:selected');
Now logic is to iterate to the previous siblings in the chain till you reach to the top.
var index = 0;
while( el.previousSibling ! == null){
el = el.previousSibling;
index +=1;
}
console.log(index);

Related

Getting undefined when trying to send select value to other page

I have a small JavaScript issue.
I have the following form:
<form method="get" name="basic" id="basicId" action="/page2">
<select id="activity" name="activity" class="form-control inputbox">
<option value="default" class="activities">Select value from dropdown:</option>
<option value="a" class="tests">A</option>
<option value="b" class="tests">B</option>
<option value="c" class="tests">C</option>
</select>
<button type="submit" id="searchBtn" placeholder="Search">Search</button>
</form>
What I'm trying to do is to get the value from the select tag and use it in page2.
For example, is option is A, the value should be ="a".
I want to use the value="a" in page2.
document.getElementById("output"): here i want to print the result in page2.
What I've tried to do in the second page:
<script>
var select = document.getElementById("activity");
var e = select.options[select.SelectedIndex].value;
document.getElementById("output").innerHTML = e;
<!-- This doesn't show anything. -->
var test = document.getElementsbyName("activity").values;
document.getElementById("output").innerHTML = test;
<!-- The output is: function values() { [native code] } -->
var test = document.getElementsByName("activity").value;
document.getElementById("opinion").innerHTML = test;
<!-- The output is: undefined -->
</script>
So basically, getting the select element by ID or by Name doesn't work.
Getting the select element ID.value doesn't work.
Getting the select element by the index doesn't work.
Any ideas? I've literally tried anything.
Am I writing the code in the wrong place?
Do I have to send this information through the server-side?
P.S.: I am writing the app in Node.js and Express and I'm using handlebars.
Kind regards,
G.
Update:
If you want to get the value to other page, you need to fetch it from url as whole new page get rendered and your old values will not exist exist.
If you are having your values in url just fetch it by this
let url = window.location
I assume, you are trying to get the value of dropdown
select has always the value attribute to it which actually is the value you select from dropdown
You just need to look for the value of select whenever you want the selected option.
Here in your case just attach a onchange listener to select, which triggers whenever the value of select get changed
var select = document.getElementById("activity");
var mySelectValue = select.value // set the default value
select.onchange = function() {
console.log(select.value)
mySelectValue = select.value // update whenever value get changed or new value chosen
}
// Do whatever you want to do with selectvalue
<form method="get" name="basic" id="basicId" action="/page2">
<select id="activity" name="activity" class="form-control inputbox">
<option value="default" class="activities">Select value from dropdown:</option>
<option value="a" class="tests">A</option>
<option value="b" class="tests">B</option>
<option value="c" class="tests">C</option>
</select>
<button type="submit" id="searchBtn" placeholder="Search">Search</button>
</form>
So basically, I have fetched the link and I tried to check if the activity = something.
example down below:
if(url.href.indexOf("activity=a") > -1){
activity = "a"
}
document.getElementById("opinion").innerHTML = activity;
Of course, in the page2, I can see "a" as a result which is great! :)

how to get values from select option box using for loop [select option box is created dynamically]

I'm trying to get values from select option box. but i get the first option box value only.
i want all option box values which is selected.suppose in code there is 10 select option box is created, when user clicks on button then i want all that 10 select option box values and get stored in a variables or display that options which is selected by the user.
i have done some code please refer my work from comment section it is on the jsfiddle website. for more better understanding you can refer that. sorry for my rookie language, i'm new to stackoverflow. please don't hesitate to edit my information i would like that.
Have a look on the following jsfiddle link:
[jsfiddle.net/ypb9zLe8/][1]
[1]: http://jsfiddle.net/ypb9zLe8/
Removed some code and inserted one extra button. Have a look.
The id for all the elements are same in your code. Use document.querySelectorAll
to get the list of elements.
function getdata() {
var num = document.getElementById("number").value;
console.log(num);
$(document).ready(function() {
for (var i = 0; i < num; i++) {
$('<div><select id="select-meal-type' + i + '"><option value="TYPE A">TYPE A</option><option value="TYPE B">TYPE B</option><option value="TYPE C">TYPE C</option></select><br></div>').appendTo('#container');
}
});
}
function getValues() {
var nodeList = document.querySelectorAll("[id^=select-meal-type]")
var values = Array.from(nodeList).map(val => val.value)
console.log(values);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<br><br> type a number<input type="text" id="number">
<br><br>
<div id="container"></div>
<button onclick="getdata()">GET DATA</button>
<button onclick="getValues()">GET VALUES</button>

Getting value from select drop-down [duplicate]

Usually I use $("#id").val() to return the value of the selected option, but this time it doesn't work.
The selected tag has the id aioConceptName
html code
<label for="name">Name</label>
<input type="text" name="name" id="name" />
<label for="aioConceptName">AIO Concept Name</label>
<select id="aioConceptName">
<option>choose io</option>
<option>roma</option>
<option>totti</option>
</select>
For dropdown options you probably want something like this:
For selected text
var conceptName = $('#aioConceptName').find(":selected").text();
For selected value
var conceptName = $('#aioConceptName').find(":selected").val();
The reason val() doesn't do the trick is because clicking an option doesn't change the value of the dropdown--it just adds the :selected property to the selected option which is a child of the dropdown.
Set the values for each of the options
<label for="aioConceptName">AIO Concept Name</label>
<select id="aioConceptName">
<option value="0">choose io</option>
<option value="1">roma</option>
<option value="2">totti</option>
</select>
$('#aioConceptName').val() didn't work because .val() returns the value attribute. To have it work properly, the value attributes must be set on each <option>.
Now you can call $('#aioConceptName').val() instead of all this :selected voodoo being suggested by others.
I stumbled across this question and developed a more concise version of Elliot BOnneville's answer:
var conceptName = $('#aioConceptName :selected').text();
or generically:
$('#id :pseudoclass')
This saves you an extra jQuery call, selects everything in one shot, and is more clear (my opinion).
Try this for value...
$("select#id_of_select_element option").filter(":selected").val();
or this for text...
$("select#id_of_select_element option").filter(":selected").text();
If you are in event context, in jQuery, you can retrieve the selected option element using :
$(this).find('option:selected') like this :
$('dropdown_selector').change(function() {
//Use $option (with the "$") to see that the variable is a jQuery object
var $option = $(this).find('option:selected');
//Added with the EDIT
var value = $option.val();//to get content of "value" attrib
var text = $option.text();//to get <option>Text</option> content
});
Edit
As mentioned by PossessWithin, My answer just answer to the question : How to select selected "Option".
Next, to get the option value, use option.val().
Have you considered using plain old javascript?
var box = document.getElementById('aioConceptName');
conceptName = box.options[box.selectedIndex].text;
See also Getting an option text/value with JavaScript
$('#aioConceptName option:selected').val();
For good practice you need to use val() to get value of selected options not text().
<label>Name</label>
<input type="text" name="name" />
<select id="aioConceptName">
<option value="choose">choose io</option>
</select>
You can use
$("#aioConceptName").find(':selected').val();
Or
$("#aioConceptName :selected").val();
Reading the value (not the text) of a select:
var status = $("#Status").val();
var status = $("#Status")[0].value;
var status = $('#Status option:selected').val();
How to disable a select?
in both variants, value can be changed using:
A
User can not interact with the dropdown. And he doesn't know what other options might exists.
$('#Status').prop('disabled', true);
B
User can see the options in the dropdown but all of them are disabled:
$('#Status option').attr('disabled', true);
In this case, $("#Status").val() will only work for jQuery versions smaller than 1.9.0. All other variants will work.
How to update a disabled select?
From code behind you can still update the value in your select. It is disabled only for users:
$("#Status").val(2);
In some cases you might need to fire events:
$("#Status").val(2).change();
With JQuery:
If you want to get the selected option text, you can use $(select element).text().
var text = $('#aioConceptName option:selected').text();
If you want to get selected option value, you can use $(select element).val().
var val = $('#aioConceptName option:selected').val();
Make sure to set value attribute in <option> tag, like:
<select id="aioConceptName">
<option value="">choose io</option>
<option value="roma(value)">roma(text)</option>
<option value="totti(value)">totti(text)</option>
</select>
With this HTML code sample, assuming last option is selected:
var text will give you totti(text)
var val will give you totti(value)
$(document).on('change','#aioConceptName' ,function(){
var val = $('#aioConceptName option:selected').val();
var text = $('#aioConceptName option:selected').text();
$('.result').text("Select Value = " + val);
$('.result').append("<br>Select Text = " + text);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="aioConceptName">
<option value="io(value)">choose io</option>
<option value="roma(value)">roma(text)</option>
<option value="totti(value)">totti(text)</option>
</select>
<p class="result"></p>
you should use this syntax:
var value = $('#Id :selected').val();
So try this Code:
var values = $('#aioConceptName :selected').val();
you can test in Fiddle: http://jsfiddle.net/PJT6r/9/
see about this answer in this post
to find correct selections with jQuery consider multiple selections can be available in html trees and confuse your expected output.
(:selected).val() or (:selected).text() will not work correct on multiple select options. So we keep an array of all selections first like .map() could do and then return the desired argument or text.
The following example illustrates those problems and offers a better approach
<select id="form-s" multiple="multiple">
<option selected>city1</option>
<option selected value="c2">city2</option>
<option value="c3">city3</option>
</select>
<select id="aioConceptName">
<option value="s1" selected >choose io</option>
<option value="s2">roma </option>
<option value="s3">totti</option>
</select>
<select id="test">
<option value="s4">paloma</option>
<option value="s5" selected >foo</option>
<option value="s6">bar</option>
</select>
<script>
$('select').change(function() {
var a=$(':selected').text(); // "city1city2choose iofoo"
var b=$(':selected').val(); // "city1" - selects just first query !
//but..
var c=$(':selected').map(function(){ // ["city1","city2","choose io","foo"]
return $(this).text();
});
var d=$(':selected').map(function(){ // ["city1","c2","s1","s5"]
return $(this).val();
});
console.log(a,b,c,d);
});
</script>
see the different bug prone output in variant a, b compared to correctly working c & d that keep all selections in an array and then return what you look for.
Just this should work:
var conceptName = $('#aioConceptName').val();
$(function() {
$('#aioConceptName').on('change', function(event) {
console.log(event.type + " event with:", $(this).val());
$(this).prev('input').val($(this).val());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>Name</label>
<input type="text" name="name" />
<select id="aioConceptName">
<option>choose io</option>
<option>roma</option>
<option>totti</option>
</select>
Using jQuery, just add a change event and get selected value or text within that handler.
If you need selected text, please use this code:
$("#aioConceptName").change(function () {
alert($("#aioConceptName :selected").text())
});
Or if you need selected value, please use this code:
$("#aioConceptName").change(function () {
alert($("#aioConceptName :selected").attr('value'))
});
For anyone who found out that best answer don't work.
Try to use:
$( "#aioConceptName option:selected" ).attr("value");
Works for me in recent projects so it is worth to look on it.
Use the jQuery.val() function for select elements, too:
The .val() method is primarily used to get the values of form elements
such as input, select and textarea. In the case of select elements, it
returns null when no option is selected and an array containing the
value of each selected option when there is at least one and it is
possible to select more because the multiple attribute is present.
$(function() {
$("#aioConceptName").on("change", function() {
$("#debug").text($("#aioConceptName").val());
}).trigger("change");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select id="aioConceptName">
<option>choose io</option>
<option>roma</option>
<option>totti</option>
</select>
<div id="debug"></div>
Straight forward and pretty easy:
Your dropdown
<select id="aioConceptName">
<option>choose io</option>
<option>roma</option>
<option>totti</option>
</select>
Jquery code to get the selected value
$('#aioConceptName').change(function() {
var $option = $(this).find('option:selected');
//Added with the EDIT
var value = $option.val(); //returns the value of the selected option.
var text = $option.text(); //returns the text of the selected option.
});
For get value of tag selected:
$('#id_Of_Parent_Selected_Tag').find(":selected").val();
And if you want to get text use this code:
$('#id_Of_Parent_Selected_Tag').find(":selected").text();
For Example:
<div id="i_am_parent_of_select_tag">
<select>
<option value="1">CR7</option>
<option value="2">MESSI</option>
</select>
</div>
<script>
$('#i_am_parent_of_select_tag').find(":selected").val();//OUTPUT:1 OR 2
$('#i_am_parent_of_select_tag').find(":selected").text();//OUTPUT:CR7 OR MESSI
</script>
You can try to debug it this way:
console.log($('#aioConceptName option:selected').val())
I hope this also helps to understand better and helps
try this below,
$('select[id="aioConceptName[]"] option:selected').each(function(key,value){
options2[$(this).val()] = $(this).text();
console.log(JSON.stringify(options2));
});
to more details please
http://www.drtuts.com/get-value-multi-select-dropdown-without-value-attribute-using-jquery/
If you want to grab the 'value' attribute instead of the text node, this will work for you:
var conceptName = $('#aioConceptName').find(":selected").attr('value');
Here is the simple solution for this issue.
$("select#aioConceptName").change(function () {
var selectedaioConceptName = $('#aioConceptName').find(":selected").val();;
console.log(selectedaioConceptName);
});
try to this one
$(document).ready(function() {
$("#name option").filter(function() {
return $(this).val() == $("#firstname").val();
}).attr('selected', true);
$("#name").live("change", function() {
$("#firstname").val($(this).find("option:selected").attr("value"));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<select id="name" name="name">
<option value="">Please select...</option>
<option value="Elvis">Elvis</option>
<option value="Frank">Frank</option>
<option value="Jim">Jim</option>
</select>
<input type="text" id="firstname" name="firstname" value="Elvis" readonly="readonly">
$('nameofDropDownList').prop('selectedIndex', whateverNumberasInt);
Imagine the DDL as an array with indexes, you are selecting one index. Choose the one which you want to set it to with your JS.
You can use $("#drpList").val();
to fetch a select with same class= name you could do this, to check if a select option is selected.
var bOK = true;
$('.optKategorien').each(function(index,el){
if($(el).find(":selected").text() == "") {
bOK = false;
}
});
I had the same issue and I figured out why it was not working on my case
The html page was divided into different html fragments and I found that I have another input field that carries the same Id of the select, which caused the val() to be always empty
I hope this saves the day for anyone who have similar issue.
Try
aioConceptName.selectedOptions[0].value
let val = aioConceptName.selectedOptions[0].value
console.log('selected value:',val);
<label>Name</label>
<input type="text" name="name" />
<select id="aioConceptName">
<option>choose io</option>
<option>roma</option>
<option>totti</option>
</select>
There is only one correct way to find selected option - by option value attribute. So take the simple code:
//find selected option
$select = $("#mySelect");
$selectedOption = $select.find( "option[value=" + $select.val() + "]" );
//get selected option text
console.log( $selectedOption.text() );
So if you have list like this:
<select id="#mySelect" >
<option value="value1" >First option</option>
<option value="value2" >Second option</option>
<option value="value3" selected >Third option</option>
</select>
If you use selected attribute for option, then find(":selected") will give incorrect result because selected attribute will stay at option forever, even user selects another option.
Even if user will selects first or second option, the result of $("select option:selected") will give two elements! So $("select :selected").text() will give a result like "First option Third option"
So use value attribute selector and don't forget to set value attribute for all options!
You many try this:
var ioConceptName = $('#ioConceptName option:selected').text();

jquery each() returns all objects as the same

Disclaimer, i am a rookie developer but am learning as i go. I have been working on this one issue for a few days now trying to interpret similar problems but to no avail.
The problem. I generate a list dynamically and each <li> has 4 input fields, 1 select box, and 2 check boxes. Values for each input are populated and the users should be able to modify. On save i am trying to use jquery to loop through the list using each() and return the values so i can push into and array/object ending up with an object for each row with name->value pairs so i can pass with ajax and save the updated input fields.
Here is the code that creates the list. (be gentle with the rookie)
echo'<li id= '.$list[id].' name="clubli" class="club">
<input type="text" name="displayorder" class="clubelement" style=" width:30px; text-align: center;" value="'.$list[display_order].'"; autofocus />
<input type="text" name="clubname" class="clubelement" value="'.$list[club_name].'" /><select id ="clubtype" name="clubtype" class="clubelement" style="width:130px;">
<option selected ="selected">'.$list[club_type].'</option>
<option id = "'.$results1[0]->id.'">'.$results1[0]->club_type.'</option>
<option id = "'.$results1[1]->id.'">'.$results1[1]->club_type.'</option>
<option id = "'.$results1[2]->id.'">'.$results1[2]->club_type.'</option>
<option id = "'.$results1[3]->id.'">'.$results1[3]->club_type.'</option>
<option id = "'.$results1[4]->id.'">'.$results1[4]->club_type.'</option>
<option id = "'.$results1[5]->id.'">'.$results1[5]->club_type.'</option>
</select>
<input style="text-align: center; width: 40px"; type="text" name="clubdist" class="clubelement" value= "'.$list[range_distance].'" /></option>
<input type="checkbox"; name="inactive"; class="clubelement"; '.$active.' /><input type=checkbox name="remove" class="clubelement"; />
<div style="margin-bottom:1em"></div></li>';
When user selects save button a JS is called which is as follows:
<script src="https://ajax.googleapis.com/ajax/libs/ jquery/1.12.0 /jquery.min.js"></script><script type="text/javascript">
function saveClubs() {
$userclubs = [];
$('.clubslist li').each(function(i) {
$id=$("[name='clubli']").attr('id');
$displayorder= $("[name='displayorder']").val();
$clubname= $("[name='clubname']").val();
$clubtype= $("[name='clubtype']").val();
$clubdist= $("[name='clubdist']").val();
$clubinactive= $("[name='inactive']").is(":checked");
$clubremove= $("[name='remove']").is(":checked");
$userclubs.push({'id':$id, 'displayorder':$displayorder, 'clubname':$clubname, 'clubtype':$clubtype, 'clubdist':$clubdist, 'inactive':$clubinactive, 'remove':$clubremove});
});
console.log($userclubs);
The console log show a result of "object" "object" "object" "object" which is expected as there are 4 rows to the list. However each object as the same 7 inputs in them - all the first row of the list. I understand that the loop is reading the first row everytime even though it is loops the expected number of times. Any guidance would be greatly appreciated....
You are close, they query selectors (e.g. $displayorder= $("[name='displayorder']").val();) are going to match the first value. So for each iteration of the loop, you only get the first matched DOM element.
To fix that, you'd need to reference the DOM element that the each() loop is currently iterating over. Something like this would work:
function saveClubs() {
$userclubs = [];
$('.clubslist li').each(function(i) {
$id=$(this).attr('id');
$displayorder= $(this).find("[name='displayorder']").val();
$clubname= $(this).find("[name='clubname']").val();
$clubtype= $(this).find("[name='clubtype']").val();
$clubdist= $(this).find("[name='clubdist']").val();
$clubinactive= $(this).find("[name='inactive']").is(":checked");
$clubremove= $(this).find("[name='remove']").is(":checked");
$userclubs.push({'id':$id, 'displayorder':$displayorder, 'clubname':$clubname, 'clubtype':$clubtype, 'clubdist':$clubdist, 'inactive':$clubinactive, 'remove':$clubremove});
});
}
Here is an example in a JS Fiddle, where you can see it working with some test data based on your PHP: https://jsfiddle.net/qg063zaL/
Hope that helps! :-)

enter text into select object

I want to enter the text selection for the following select field:
<select name="Payerid" id="Payerid" class="text" name="Payerid">
<option value="383">Aetna Healthcare</option>
...
Using VBA, I know I can use: (If you give me the syntax in another language, I'll convert)
IE.getElementById("Payerid").Value = "383"
but there about 100 options so I don't want to keep track of the values (which are meaningless to me) or changes the website developers make.
So is there a way to enter the text into the select field?
I tried:
IE.getElementById("Payerid").Text = "Aetna Healthcare"
but that didn't work.
Thanks
You mean you want to change the value? That's just $('select').val('value you want');, using Jquery.
If you're wanting to obtain the value based on what is in the text field, that is as below, derived in part from this post.
var pick = "hey";
var value_pick = $('option').filter(function () { return $(this).html() == pick; }).val();
console.log(value_pick);
$("select").val(value_pick);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select>
<option value="1" >hey</option>
<option value="1" >baha</option>
<option value="1" >yo</option>
</select>

Categories

Resources