Add a value with the <select> option - javascript

I need to add the value of a variable to the value of the option.
Option values ​​are redeemed through a spreadsheet in Google Docs.
PROJECT ONLINE
spreadsheet with values
I'm using the code below to retrieve the values:
//Add value with fee
$(document).ready(function() {
var sheetURL ="https://spreadsheets.google.com/feeds/list/1J0qyxUCCkvcFGZ6EIy9nDOgEuTlpI5ICVG3ZsBd_H-I/1/public/values?alt=json";
$.getJSON(sheetURL, function(data) {
var entryData = data.feed.entry;
console.log(data);
jQuery.each(entryData, function() {
$("#totalSumWithFee").append(
'<option hidden="hidden" selected="selected" value="default">Choice</option><option value="' + this.gsx$values.$t + '">' + this.gsx$names.$t + '</option>'
);
});
});
});
This part is working. So, I tried to add the following code:
//new code
var valueSelectedFee = $('#totalSumWithFee :selected').val();
var cart = 10;
var cartWithFee = cart + valueSelectedFee;
$('.total-sum').html(cartWithFee.toFixed(2));
But NaN value is returning. Below is the HTML:
<strong>Total: $ <span class="total-sum"></span></strong>
<br><br>
<select style="width: 200px;" id="totalSumWithFee"></select>
How could I use the option values ​​without returning the NaN value?

Because your initial code sets the first "Choice" option as the "selected" option, whose value is "default" (which is not a number), the line in the second section of code:
var cartWithFee = cart + valueSelectedFee;
is trying to set "cartWithFee" to 10 + "default", adding a string to a number, which doesn't work. If you change that line to:
var cartWithFee = cart + (isNaN(valueSelectedFee) ? 0 : valueSelectedFee);
then it will replace any NaN values (like "default") to 0, and should work correctly.

Related

fill the input type hidden from selected multiple option on jquery

I have a input that have type like this:
<input class="emailSend" name="emailSend" type="hidden">
Then I have a multiple select option like this
<div class="controls">
<select id="email" multiple data-rel="chosen" class="input-xlarge" name="email[]">
<?php
foreach ($atasan as $data) {
echo "<option value='" . $data['email'] . "'>" . $data['email'] . "</option>";
}
?>
</select>
</div>
My problem is, I want to fill that hidden input from the option that selected from multiple select option. So let say, the selected option is 'email1', 'email2', 'email3' then would be affected to hidden type like this 'email1, email2, email3'.
I have try this for 3 hour in jquery and I am stuck. My code is like this.
$("#email").change(function() {
var elements = $("#email option:selected").length;
var input = $(".emailSend");
$(".emailSend").html("");
$.each($("#email option:selected"), function(/*index, element*/) {
input.val(input.val() + $(this).html() + ", ");
if (index < elements - 1) {
//code to remove last comma
//any idea ?
}
});
});
So appreciated for the help...
EDIT Here is the fiddle :JSFIDDLE
Updated FIDDLE now that I see what you meant by looking at the fiddle you made.
this is actually all you need to do...
Updated to include spaces between the addresses!
$("#email").on('change', function() {
var thisval = $(this).val() + '';
var myarr = thisval.split(',');
var newval = '';
myarr.forEach(function(i,v) {
newval += i + ' , ';
});
newval = newval.slice(0, newval.length - 3);
$("#emailsend").val(newval);
});
Commented Version (for learning and stuff)
$("#email").on('change', function() {
//the extra space at the end is to typecast to string
var thisval = $(this).val() + '';
//takes string of comma separated values and puts them
//into an array
var myarr = thisval.split(',');
//Initialize a new string variable and loop through
//the array we just created with MDN's forEach()
var newval = '';
myarr.forEach(function(i,v) {
//add to the string through each iteration,
//including comma with spaces
newval += i + ' , ';
});
//use .slice() to trim three characters off the
//end of the final string. (strip final comma)
newval = newval.slice(0, newval.length - 3);
//and last but not least, assign our newly created
//and properly formatted string to our input element.
$("#emailsend").val(newval);
});

Trying to connect a dynamically created select element (tag) with options to a dynamically created table row

The first block of code is a working example of what I want the variable select to do. the var Select is there to be a td in the variable tr. the variable tr is used 2 times in this code. once to to append the tr when the table has html and another time when it doesn't have any html. the reason is because if doesn't have html it should append the header and the row with the select element and the rest of the data that's supposed to be on the row and if does have html it should only append the row to prevent repetition of the header. so I would like a nice clean variable named tr that will be append every time the users invokes it. jsfidle if you click on the drop down you could select the item and the new row will appear.
$('#autocomplete').autocomplete({
lookup: currencies,
onSelect: function (suggestion) {
var thehtml = '<strong>Item:</strong> ' + suggestion.value + ' <br> <strong>price:</strong> ' + suggestion.data + "<br>" + suggestion.divs;
var tableheader = ($("<thead>")
.append($("<tr>")
.append($("<th>Item</th><th>Qty</th><th>Price</th>")))
)
var select = " <select class = 'select'><option value='volvo>Volvo</option> <option value='saab'>Saab</option> <option value='mercedes'>Mercedes</option> <option value='audi'>Audi</option> </select>"
var tr = "<tr><td>"+ suggestion.value + "</td><td>" +select +"</td></tr>"
if($(".table").html().length <= 0)
{
$('.table').append($("<table>")).append(tableheader).append(tr);
}else{
if($(".table").html().length > 0){
$(".table").append(tr)
}
}
The thing is I want the select element to be made up dynamically so i tried something and I cant figure out why it wont work. It's not recieving the variable. Am i implementing the varable wrong with the $.each?
$('#autocomplete').autocomplete({
lookup: currencies,
onSelect: function (suggestion) {
var thehtml = '<strong>Item:</strong> ' + suggestion.value + ' <br> <strong>price:</strong> ' + suggestion.data + "<br>" + suggestion.divs;
var tableheader = ($("<thead>")
.append($("<tr>")
.append($("<th>Item</th><th>Qty</th><th>Price</th>")))
)
var selectValues = { "3": "2", "2": "1" , "1": "..."};
var select = $.each(selectValues, function(key, value){
$('.select').append($('<option>', {value: value}).text(value));
// <option value='volvo>Volvo</option>
});
var tr = "<tr><td>"+ suggestion.value + "</td><td><select class ='select'>" + select + "</select></td></tr>";
if($(".table").html().length <= 0)
{
$('.table').append($("<table>")).append(tableheader).append(tr);
}else{
if($(".table").html().length > 0){
$(".table").append(tr)
}
}
},
maxHeight:100,
width:600
});
thanks for your help
Why use object if you use only value?
if you realy don't need key juste create an array :
var selectValues = ["2", "1", "..."];
var value;
var select = selectValues.forEach(function(value){
$('.select').append($('<option>', {value: value}).text(value));
// <option value='volvo>Volvo</option>
});
// or if you want more compatibility
for (var i = 0, len = selectValue.length; i < len; i++) {
value = selectValue[i];
$('.select').append($('<option>', {value: value}).text(value));
});
Edit:
i make some mistake sorry.
first forEach will return nothing so it's can't work.
I test with your fidle. try this (replace by old for loop if you don't want to use map).
var select = selectValues.map(function(value){
return "<option value=" + value + ">" + value + "</option>";
// <option value='volvo>Volvo</option>
}).join('');
first you do not have to append from $('.select') because this dom not exist at this moment
and you can't concate an array in a string like this.

javascript, selection option using for loop that return the selected value

I'm pretty new to javascript so please bear with me. I'm trying to create a drop down list of age choice from 1-100, with option 20 show as default. I also need to get the return value of the choice user selected so i can use to calculate the years. Here is the code i'm playing around with so far.
function createAgeList()
{
var myAgeOptions;
for (cntr=1; cntr<100; cntr++)
{
myAgeOptions = myAgeOptions + "<option value=" + cntr + ">" + cntr + "</option>";
}
var myAgeSelect = document.getElementById('agelist');
myAgeSelect.innerHTML = myAgeOptions;
}
HTML code:
<form name="yearsleptform" id="yearsleptform" method="post">
<select size="1" id="agelist" name="agelist">
</select>
</form>
document.yearsleptform.agelist.value
This is going to return you the value they have selected.
To set the default option:
function createAgeList()
{
var myAgeOptions;
for (cntr=1; cntr<100; cntr++)
{
myAgeOptions = myAgeOptions + "<option value=" + cntr + " "+(cntr===20?"selected=selected":"")+ ">" + cntr + "</option>";
}
var myAgeSelect = document.getElementById('agelist');
Live Demo
myAgeSelect.innerHTML = myAgeOptions;
}
to get the selected value:
document.yearsleptform.agelist.value
Live Demo

Getting a SelectList obejct from a ListBox and placing into an HTML Selection List

Say I have a ListBox populated with a name value pair SelectList(myUsers, "Key", "Value"):
#Html.ListBox("ListReviewers", (SelectList)ViewBag.ListOFReviewers, new { style = "width:120px;" })
I want to double click an option in this ListBox, and place it in a SelectionList like below:
<div class="selectedEmployees">
<select class="selectionList" multiple="multiple" name="AssignedReviewer" style="width:120px;">
<!--x.UserID, x.FirstName + " " + x.LastName) -->
<option value=""></option>
</select>
</div>
Once this collection is placed in the above, I want to store all the values in another SelectionList Collection for later use.
Here is the start of my jQuery code:
<script type="text/javascript">
$('#ListReviewers').dblclick(function (i, selected) {
//double click on this value of listbox of type SelectList(myUsers, "Key", "Value")
//store this value and text
var value = $(this).val;
//var empName = $(this).data[0];
var empName = $(selected).text();
alert(empName);
//append an option element <option value=""></option>
$('.selectionList').append('<option id="' + value + '">' + empName + '</option>');
});
I can get the value of the dblclicked collection object, but not the text of the collection object. Is there a better way to do this?
Try attaching your event to the option within the select itself. You can then use this to access it's properties.
$('#ListReviewers option').dblclick(function () {
var value = $(this).val();
var empName = $(this).text();
$('.selectionList').append('<option id="' + value + '">' + empName + '</option>');
});
Alternatively, you can use clone() and append() to move the option from one select to the other. This will save you having to worry about duplicate options being appended.
$('#ListReviewers option').dblclick(function () {
var $newOptions = $(this).clone(false);
$(this).remove();
$('.selectionList').append($newOption);
});

popualte textbox from values on screen with javascript

how can I use the values from the code below:
<html:select property="state" >
<html:option value="0">Select State</html:option>
<html:optionsCollection name="InputForm" property="stateList" label="label" value="value" />
</html:select>
to populate a textbox with whatever the selected value is for the state with a javascript onchange event? for example if texas is the selected state I want Texas to be written in the textbox and if I change the value to Colorado I would like Colorado and Texas to both show in the textbox. I am currently getting an undefined value in the textbox. I am using the following javascript code:
function displayState(obj, state) {
var theId = obj.id.substring(obj.id.indexOf('_') + 1);
var text = document.getElementById('text' + '_' + theId);
var textVal = text.value;
var stateSelect = document.getElementById('stateCode' + '_' + theId);
var stateSelectStr = new String(stateSelect.value);
var stateSelectSplit = stateSelectStr.split(',');
var stateSelectValue = stateSelectSplit[0];
var stateSelectLabel = stateSelectSplit[1];
if (stateSelectValue == '51') {
stateSelectLabel = '';
}
if (stateSelectValue != '00') {
textVal = textVal != '' ? eval('text.value=\'' + textVal + ', '
+ stateSelectLabel + '\'')
: eval('text.value=\'' + stateSelectLabel + '\'');
}
}
First off, start using jQuery (or equivalent), it will make your life much easier. Second, why are you using eval? You already have the text element; just build the appropriate string and set the value. See here for an example.
But again, using something like jQuery makes this laughably easy--I can't recommend using a library for simple DOM manipulation like this.
See here for a comparison between raw JS and JQ.

Categories

Resources