use option output rather than option value - javascript

I have a simple jquery script set up to calculate the cost of services for a user. the script works great! However, my database side calls to go another route. How can I use the actual output of the option for the calculation rather than the value
jquery:
var $selections = $('#selections');
var $selects = $("select").change(function () {
var total = 0;
$selections.empty();
$selects.each(function () {
var $selected = $(this).find("option:selected");
var price = parseFloat($selected.data("price")) || 0;
total += price;
if($selected.val() !== ''){
$('<li />', {
text: $selected.val() + $(this).parent().clone().children().remove().end().text()+" " + $selected.data("price")
}).appendTo($selections)
}
})
$(".summary").text('Est. Total $' + total);
})
HTML with PHP:
<select name="rooms" id="Areas">
<option value="" selected="selected">0</option>
#foreach ($room as $rooms)
<option data-price="{{ $rooms->pr_clean }}" value='{{ $rooms->room }}'>{{ $rooms->room }}</option>
#endforeach
</select>
Basically I want to be able to add something different in the value field to go into the database but still calculate how many room they are wanting to select using {{ $rooms->room }}
here is a fiddle with the basic idea of how my script works. http://jsfiddle.net/arunpjohny/xf9Fp/

In jQuery .val() will give you the option's value when defined inside the <option> tag. If there is no value in the option it will get the text of the option.
<option value="" selected="selected">0</option>
^------^ ^
value text
So because some of your options have value="", jQuery's .val() will get that value, which is a empty string. Without value="" inside the <option> tag .val() would give you 0.
To be sure you always get the text of the option you can use .text().
So use this: if($selected.text() !== ''){

Related

Get the values of all select options on change event javascript

I want to know all the values of a select element once the change event is recorded on it.
Code is like this:
PHP
<select name='variant' class='variantsselect' onchange='on(this.value)'>
<option value='a'>a</option>
<option value='a'>a</option>
</select>
JAVASCRIPT
function on(value){
alert(value); //This gives me selected value
};
I need values a & b when change event is recorded on select element. Can someone help?
<select name='variant' class='variantsselect' onchange="javascript:valueselect(this)">
function valueselect(sel) {
var value = sel.options[sel.selectedIndex].value;
alert(value)
}
EDIT:
<select name='variant' id='variant' class='variantsselect' onchange="javascript:displayResult()">
function displayResult() {
var x = document.getElementById("variant");
var i;
var txt = "Text: ";
for (i = 0; i < x.length; i++) {
txt = txt + "\n" + x.options[i].text;
}
alert(txt);
}
You can store the last selected value in a variable and overwrite the variable with the new selected value at the end of your function. When the function is called the variable will = to the last option selected (If you don't set a default value the variable will be empty on the first call)
Click Here For Demo
OR
This will work for a simple hide/show select without having to remember the previous selection.
The hide/show content have a class name of HideShow, this class name css display is set to none. When you change the option it will loop through all elements using the class name HideShow to compare the selected value with the id of the element, if they match it will set the style display to block }else{ set style display to none.
Demo
function HideShow(Selection){
var HScontent=document.getElementsByClassName('HideShow');
for(var i=0; i<HScontent.length; i++){
if(HScontent[i].id==Selection){
HScontent[i].style.display="block";
}else{
HScontent[i].style.display="none";
}
}
}
.HideShow{display:none;}
<select onchange="HideShow(this.value);">
<option value="cars">Cars</option>
<option value="bikes">Bikes</option>
<option value="buses">Buses</option>
</select>
<div id="cars" class="HideShow">Cars content.....</div>
<div id="bikes" class="HideShow">Bikes content....</div>
<div id="buses" class="HideShow">Buses content....</div>
If you don't understand something in the demo, leave a comment below and I will try get back to you as soon as possible.
I hope this helps. Happy coding!

How can I put selected value of jquery multiselect dropdown into a hidden element's id

How can I put selected value of jquery multiselect dropdown into a hidden element's id? I need that id be an array so I can get the selected values of the multiselect into that.
What I tried is:
$( "#Myselect" ).change(function(){
var str = "";
$( "select option:selected" ).each(function() {
str += $( this ).val() + " ";
});
document.getElementById("objecttype").value = str;
}).trigger( "change" );
<html:hidden styleId="objecttype" property="objecttype" name="Myobjecttype"/>
but objecttype is just an id and isn't an array!
I assume you want this hidden field to be posted somewhere and used later on (server-side or whatever). Take a look at this Fiddle: http://jsfiddle.net/hm71689h/ it is roughly what you wanted.
Take into account what Haxxxton just said: you're joining the values using a delimiter (in this example a comma by default). You need to split that value into a new array later on.
Also, in your code-sample, you're referring to the hidden field using: document.getElementById("objecttype")
But you did not use an identifier, you used a name. Although you might think it should be the same, an ID is not the same as the name of an element.
I think you need smth like this:
HTML:
<select name="choice" multiple id="mySelect">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<input type="hidden" name="myObjecttype" />
JS:
$('#mySelect').change(function(){
//brand new array each time
var foo = [];
//fills the array
foo = $("option:selected", this).map(function(){ return $(this).val() }).get();
//fills input with vals, as strings of course
$("input[name='myObjecttype']").val(foo);
//logs an array, if needed
console.log($("input[name='myObjecttype']").val().split(','));
});
Don't forget hidden input can't store array-/object- data, only strings. But you can easily make array.
See working jsfiddle: http://jsfiddle.net/sfvx5Loj/1/

js change select name based on option selection

I have a dynamic drop down menu where options are loaded from database, Now i need to change the attribute every time different option is selected from the drop down menu.
To achieve this I am trying to use js in my opinion suitable to do the job but unfortunately I find it difficult and cannot come up with a correct solution, actually i dont know how to start it.
Here is my PHP code that dynamicly generates drop down menu:
$opt = '<select id="Forex" name="" style="display: none">';
$opt1 = '<option value="">Select Forex Workshop</option>';
$opt2 = '';
while($result = mysqli_fetch_assoc($query)){
if($timestamp < $result['endingDate']){
$opt2 .= '<option id="'.$result['id'].'" value="'.$result['startingDate'].'">'.$result['course'].'</option>';
}
}
$opt3 = '</select>';
return $opt.$opt1.$opt2.$opt3;
Could some one suggest a solution a at least give me a link to a article that covers this problem
You can add "onchange" event and change the name whatever you like:
$('#Forex').change(function(){
var val = $(this).val(); // you can get the value of selected option
//you can process your conditions here
$(this).attr('name', 'your_choice_name'); // this will change the name attribute
});
or you can do this from javascript
<select id="Forex" name="abc" onchange="changeAttr(this);">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
<script type="text/javascript">
function changeAttr(ele)
{
var val = ele.value;
var n = "";
if(val == 1){
n = 'xyz';
} else if(val == 2){
n = 'abc';
}
ele.setAttribute('name', n);
}
</script>
Hope this will help you what you want...
Use jquery, with a "onChange" event that will change the attribute you want with the selected item in the list.
jQuery get value of select onChange
Hei!
Not sure if I understood you, but you can use jQuery to manipulate attributes on change event.
For event http://api.jquery.com/change/
To change atribute http://api.jquery.com/attr/

How to assign an ID to a dynamic dropdown select?

I want to assign a session ID (this will be hidden) whenever the first select dropdown is used. The session ID is the number 300, 301, etc. after the "day".
When a user selects something from the "preferred" dropdown it should assign the "300" value to the "sessionid" dropdown and simultaneously change the value of the "day" dropdown (which works already btw)
How do I do implement it properly?
Please see code below:
<select id="preferred" class="preferred" name="preferred">
<option value="">- Select -</option>
<option value="Mountain Dew">Mountain Dew</option>
<option value="Seven Up">Seven Up</option>
</select>
<select id="day" class="day" name="day">
<option value=""></option>
</select>
<select id="sessionid" class="sessionid" name="sessionid">
<option value=""></option>
</select>
$(function() {
var selectValues = {
"Mountain Dew": {
"Monday": "300"
},
"Seven Up": {
"Tuesday": "301"
}
};
var $preferred = $('select.preferred');
var $day = $('select.day');
var $sessionid = $('select.sessionid');
$preferred.change(function() {
$day.empty().append(function() {
var output = '';
$.each(selectValues[$preferred.val()], function(key, value) {
output += '<option value="' + key + '">' + key + '</option>';
});
return output;
});
}).change();
});
example : http://jsfiddle.net/creativemix/5ZWrE/2/
Try this if you want to set the value of session id dropdown. Include this after setting the output variable in your fiddle.
$sessionid.empty()
.append($("<option></option>")
.attr("value",value)
.text(value));
Here's a link to the fiddle.
But, as others already suggested, why not use a hidden text field to store the value?
To store the value in a hidden field,
<input type="hidden" id="hdnSessionId" />
And add this to the script.
$('#hdnSessionId').val(value);
You can use Element.id = 'id' to set an id in javascript.
https://developer.mozilla.org/en-US/docs/Web/API/Element.id
In your code that would probably be something like this at the point where you want to assign the id:
$sessionid[0].id = $day.val();
But please note an id must start with a letter and numbers are generally bad practice even if it does work.
Putting the value you need in a hidden field is probably preferable over this solution.

jQuery Select list, selected text value rather than the value

building on my last question jQuery getting values from multiple selects together
I have the select list like:
<select name="access" class="change" id="staff_off" runat="server">
<option value="8192">Off</option>
<option value="8192">On</option>
</select>
And I basically want to add or subtract the value of the options if it's off, subtract if it's on add it. It's going to be stored in a cookie (it uses bitwise)
The jquery I have is:
<script>
$(document).ready(function(){
var currentAccess = $.cookie("access");
})
$("select").change(function () {
var currentText = $(this).text()
var value = $(this).val()
$.cookie("access", value, { expires: 24 });
alert(currentText);
alert( $.cookie("access") );
})
</script>
I'll do the addition in the change function. The thing I can't work out is how to get the text of the select to do an if statement (so if it's yes, add the value, if it's no, subtract the value)
Tom
If you're looking for the inner text of the selected <option> element, you can use the :selected selector to match it, then call the text() method:
var currentText = $(this).find(":selected").text();
Or, alternatively:
var currentText = $(":selected", this).text();
To get the text of the selected item:
var value = $("#staff_off :selected").text();
I'd also suggest (if you're using HTML5) that using the data-x attribute to store the flag whether to add or subtract the value would be more semantic. Like this:
<select name="access" class="change" id="staff_off" runat="server">
<option value="8192" data-factor="-1">Off</option>
<option value="8192" data-factor="1">On</option>
</select>
Then to get your final value to apply to the total you simply multiply the value by the data-factor attribute.
You can use this $("#staff_off").find("option:selected").html();

Categories

Resources