Need to $post text of select boxes, not their values - javascript

Need to $post text of select boxes, not their values.
HTML :
<select name="one" id="one">
<option value="0">Select *</option>
<option value="3000">Plan A</option>
<option value="6000">Plan B</option>
<option value="9000">Plan C</option>
</select>
<br />
<select name="two" id="two">
<option>Please choose from above</option>
</select>
<div id="total"></div>
JS :
// arrays instead of comma separated list and added base key
var data = {
"0": ["Please choose from above"],
"3000": ["saad_0", "Coffee_465", "Coke_984"],
"6000": ["saad_0", "Coffee_465", "Coke_984"],
"9000": ["saad_0", "Chips_123", "Cookies_987"]
}
$("#one").change(function () {
var first = $(this),
second = $("#two"),
key = first.val(),
// instead of the original switch code
vals = data[key] == undefined ? data.base : data[key],
html = [];
// create insert html before adding
$.each(vals, function (i, val) {
var v = val.split('_');
html.push('<option value="' + v[1] + '">' + v[0] + '</option>')
});
// no need to empty the element before adding the new content
second.html(html.join());
});
$("#one,#two").change(function () {
var val1 = parseInt($('#one').val()) || 0,
val2 = parseInt($('#two').val()) || 0;
$('#total').text(val1 + val2)
})
What I'm using :
$message .= "<br>One : " . $_POST['one'];
$message .= "<br>Two : " . $_POST['two'];
And in email result I'm getting values, which I don't want. As values are only needed for calculation.
Someone told me to bind my post method with jquery, which I have no idea about it.
Demo : jsfiddle link

$("#yourdropdownid option:selected").text();

Related

Is there a different way to update the wrapper for when dynamically updating dropdown checklst

I trying to create a html and java script front-end for my python back-end. I am parsing the data from a tsv file and then dynamically updating the drop down list. I don't have much experience with html and javascript and am trying to learn.
I am using jQuery drop down multiselect
<form id="form-user" action="#" method="post">
<center>
<select id='testSelect1' multiple>
<option value='1'>Item 1</option>
<option value='2'>Item 2</option>
<option value='3'>Item 3</option>
<option value='4'>Item 4</option>
<option value='5'>Item 5</option>
<option value='1'>Item 1</option>
<option value='2'>Item 2</option>
</select>
</center>
</form>
Code for html layout
$('#testSelect1').multiselect({
columns: 1,
placeholder: 'Select Shoporder',
selectAll: true,
minCount: 30
});
This is how I am initializing it:
function updateShopOrder(data) {
var inner_HTML = [];
var temp = "<option value=";
const element = document.getElementById('testSelect1');
var value = "hello";
$(document).ready(function() {
for (i = 0; i < 20; i++) {
//var newOption = document.createElement("option");
//newOption.value = "tt";
//newOption.text = "test";
//element.add(newOption);
element.innerHTML += temp.concat(i.toString(), ">", "item ", i.toString(), "</option>");
//document.multiselect('#testSelect1').append("<option value=\"" + i.toString() + "\">" + value
+ " </option>");
//$('#testSelect1').multiselect( 'refresh' );
//$('#testSelect1').multiselect( 'rebuild' );
}
});
}
Code for how i am trying to update the the list. Commented out are stack overflow solutions I tried before. However everything I tried so far updates the html but does not update the wrapper (observation from devtools) enter image description here.
Any help would be greatly appreciated.
// DYNAMICALLY LOAD OPTIONS
$('select[multiple]').multiselect( 'loadOptions', [{
name : 'Option Name 1',
value : 'option-value-1',
checked: false,
attributes : {
custom1: 'value1',
custom2: 'value2'
}
},{
name : 'Option Name 2',
value : 'option-value-2',
checked: false,
attributes : {
custom1: 'value1',
custom2: 'value2'
}
}]);
I found this in the documentation but how would i go about implementing it using a for loop?
Try this code
$.each(data, function (index, value) {
// APPEND OR INSERT DATA TO SELECT ELEMENT.
$('#testSelect1').append('<option value="' + value.ID + '">' + value.Name + '</option>');
});
Iterate over your data somehow and append that to the html file. Refresh periodically for the change to reflect in your html

Related selects using jquery not working as expected

I don't do a whole lot with jquery, so please forgive if this is a really entry level question. I have two selects - broad categories of academic interests and then refined based on the first selection. Firebug shows me getting the correct data back from the function, but I can't get it to build the 2nd select with that data.
<script>
$("#general").change(function() {
$.ajaxSetup({
dataFilter: function(data, type){
return type == 'json' ? data.replace(/^(\/{2})?/, '') : data;
}
});
//get what they selected
var selected = $("option:selected",this).val();
//no matter what, clear the other DD
$("#majors").children().remove().end().append("<option value=\"\">-- Select a Majors --</option>");
//now load in new options of selected category
if(selected == "") return;
$.getJSON(remote.cfc?method=queryMajorsRemote&returnformat=json",{"cip_fam":selected}, function(res,code) {
var newoptions = "";
for (var i = 0; i < res.DATA.length; i++) {
newoptions += "<option value=\"" + res[i].id + "\">" + res[i].name + "</option>";
}
$("#majors").children().end().append(newoptions);
});
});
</script>
The HTML is very simple - just two selects - one with ID #general and the other with ID #majors.
A sample of the response data is:
[{"ID":422,"NAME":"Engineering"},{"ID":426,"NAME":"Engineering - Aerospace, Aeronautical and Astronautical"}]
According to the sample of the response data reported in the question, you have some issues:
res.DATA.length must be res.length
res[i].id must be res[i].ID
res[i].name must be res[i].NAME
In order to create a new option you may write on the fly, instead of string:
$('<option/>', {value: res[i].ID, text: res[i].NAME})
If you need to empty the second select box before appending options you may write:
$("#majors").empty()
The snippet:
var res = [{"ID":422,"NAME":"Engineering"},{"ID":426,"NAME":"Engineering - Aerospace, Aeronautical and Astronautical"}];
$("#general").change(function () {
$.ajaxSetup({
dataFilter: function (data, type) {
return type == 'json' ? data.replace(/^(\/{2})?/, '') : data;
}
});
//get what they selected
var selected = $("option:selected", this).val();
//no matter what, clear the other DD
$("#majors").children().remove().end().append("<option value=\"\">-- Select a Majors --</option>");
//now load in new options of selected category
if (selected == "") return;
//$.getJSON("http://localhost:63342/Projects/StackOverflow/1.json", {"cip_fam": selected}, function (res, code) {
var optionToBeAppendedTo = $("#majors").empty();
for (var i = 0; i < res.length; i++) {
optionToBeAppendedTo.append($('<option/>', {value: res[i].ID, text: res[i].NAME}));
}
//});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="general">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select id="majors">
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
<option value="40">40</option>
</select>

How to keep drop down menu variable by function

i have a function with 3 cases depending on the date. Now i want to display it in a drop down menu.
function get_data_date(i) {
var string;
if (i == 0) {
if(d.getUTCHours() < 3 ) {
.
.
.
.
.
string=d_date.getUTCFullYear()+""+addZero1(d_date.getUTCMonth()+1)+""+d_date.getUTCDate()+"_"+addZero1(d_date.getUTCHours());
return string;
}
I do not know how to call the function in an Option tag. Please note that the function is not complete displayed.
<form action="select.htm">
<select name="run" size="1">
<option id="run1" > get_data_date(0)</option>
<option id="run2" > get_data_date(1) </option>
<option id="run3" > get_data_date(2)</option>
</select>
</form>
Don't use eval, as it offers too many opportunities for Bad Things.
Instead, inspect the selected option and invoke the appropriate function. With the markup as you've presented it, it would look something like this
// Ignore this, it's just here for an example
var doLog = (function() {
var logOutput = document.createElement('pre');
document.body.appendChild(logOutput);
return function doLog(msg) {
var t = document.createTextNode(msg + "\n");
logOutput.appendChild(t);
};
})();
function get_data_date(i) {
doLog('You selected ' + i);
}
function selectChangeHandler(ev) {
var e = ev.target;
var id = e.options[e.selectedIndex].id;
// Invoke `get_data_date` with appropriate argument, based on
// the selected option. NOTE: This is not a good solution--see below for
// a better one
if (id === 'run1') {
get_data_date(0);
} else if (id === 'run2') {
get_data_date(1);
} else if (id === 'run3') {
get_data_date(2);
}
}
var selectControl = document.querySelector('select[name="run"]');
selectControl.addEventListener('change', selectChangeHandler);
<form action="select.htm">
<select name="run" size="1">
<option id="run1" > get_data_date(0)</option>
<option id="run2" > get_data_date(1) </option>
<option id="run3" > get_data_date(2)</option>
</select>
</form>
However, if you have control of your markup, you should consider refactoring to put the value you care about in the value attribute of your options. Then, you can directly access that value and pass it as an argument to your function.
// Ignore this, it's just here for an example
var doLog = (function() {
var logOutput = document.createElement('pre');
document.body.appendChild(logOutput);
return function doLog(msg) {
var t = document.createTextNode(msg + "\n");
logOutput.appendChild(t);
};
})();
function get_data_date(i) {
doLog('You selected ' + i);
}
function selectChangeHandler(ev) {
var e = ev.target;
// TODO: Error handling
var val = e.options[e.selectedIndex].value;
get_data_date(val);
}
var selectControl = document.getElementById('date-run-select');
selectControl.addEventListener('change', selectChangeHandler);
<form action="select.htm">
<select id="date-run-select" name="run" size="1">
<option id="run1" value="0"> get_data_date(0)</option>
<option id="run2" value="1"> get_data_date(1) </option>
<option id="run3" value="2"> get_data_date(2)</option>
</select>
</form>

2 variables from select box and hidden input

How can I get 2 different variables from select box and hidden inputs in jquery, i.e:
<select name="startID[]" class="startID">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="hidden" name="startText[]" value="Text1">
<br />
<select name="startID[]" class="startID">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="hidden" name="startText[]" value="Text2">
<br />
<select name="startID[]" class="startID">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="hidden" name="startText[]" value="Text3">
so I have 3 select boxes with 3 hidden inputs, how can I get the value of each select boxed and the text that is attached to? i.e: if I select like this:
Select item is 1 and text is Text1
Select item is 3 and text is Text2
Select item is 2 and text is Text3
Thanks in advance
function getValues() {
$('select').each(function (idx, el) {
console.log("Select item is " + $(el).val() + " and text is " + $(el).next('input[type="hidden"]').val());
});
}
If you want to list the values on change:
$('select.startID,input[type="hidden"]').change(getValues);
Demo (modified a bit):
http://jsfiddle.net/6ev9evew/
NOTE
The updates below are not answers for the original question, but the question's author keeps posting extra questions in the comments! So the solution is above!
UPDATE:
As I can understand this is what you looking for:
function getValues() {
var me = this;
$('select').each(function (idx, el) {
console.log("Select item is " + $(el).val() + " and text is " + $(el).next('input[type="hidden"]').val());
if (el === me) return false;
});
}
So basically we stop the loop at the actual element. But it works only if you pass this function to an event handler.
DEMO 2: http://jsfiddle.net/6ev9evew/1/
UPDATE 2:
So, according to the third question, this is a version of the implementation. As I mentioned below in the comments section, there are multiple ways to implement it. This implementation uses that the array indexes are always in order.
function getValues() {
var result = [];
var me = this;
$('select').each(function (idx, el) {
var $el = $(el);
result[10*$el.val()+idx]=("Select item is " + $el.val() + " and text is " + $el.next('input[type="hidden"]').val()+'<br />');
if (me === el) return false;
});
$('#res').html(result.join(''));
}
$('select.startID,input[type="hidden"]').change(getValues);
DEMO 3:
http://jsfiddle.net/6ev9evew/2/
But you can also implement it with array.sort(fn) but than you do a second iteration on the result set.
Anyway if you have more than ten selects in your real code, don't forget to modify the multiplier at result[10*$el.val()+idx] !
If you want to know the value of the changed select (when the user selects a value on any of them) and also get the value of the input type hidden which is next to it, that's the way:
$('.startID').on('change', function () {
var sel = $(this).val();
var hid = $(this).next('input[type=hidden]').val();
console.log('Select item is ' + sel.toString() + ' and text is ' + hid.toString());
});
Demo
UPDATE
To achieve what you've asked in the comments, you can do it like this:
// Create two arrays to store the values.
var sel = [];
var hid = [];
$('.startID').on('change', function () {
// Put the selected values into the arrays.
sel.push($(this).val());
hid.push($(this).next('input[type=hidden]').val());
console.log(sel);
console.log(hid);
for (var i = 0; i < sel.length; i++) {
console.log('Select item is ' + sel[i].toString() + ' and text is ' + hid[i].toString());
}
});
Demo

Setting default value of <select> element

I have a table in my webpage that captures the details of a previous order history. The table has the following columns:
Order Date Review
Now, for the review, I want to have a select dropdown with some options. When user first launches the page, I want the previous rating to show up as default in the select dropdown. Here is what my code looks like:
tds.push( {
content: '<select id="clientReview" name="clientReview" value=' + obj.get("client_review") + '>' +
'<option value=1>Hate it!</option>' +
'<option value=2>Don't love it but don't hate it.</option>' +
'<option value=3>Fantastic!</option>'
});
I was expecting that setting the value in select would set the default value in the dropdown but that's not happening. I still see the first value as default. Any idea how I can fix that?
What about setting of value after inserting of HTML to document?
HTML:
<select id="dropdown">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<input id="textField" type="text" value="2" />
JavaScript:
(function() {
var dropdown$ = $('#dropdown'),
textField$ = $('#textField');
function changeVal() {
var val = parseInt(textField$.val());
if(!!val && val > 0 && val < 4) {
dropdown$.val(val);
}
}
textField$.on('keyup', changeVal);
changeVal();
})();​
DEMO
<option value="1" selected="selected">Text</option>
See:
http://www.w3.org/wiki/HTML/Elements/option#HTML_Attributes
http://www.w3schools.com/tags/att_option_selected.asp
Based on your code example I can assume that you'll use this HTML to insert somewhere later. In this case you can have something like next code:
tds.push( {
content: '<select id="clientReview" name="clientReview" data-value="' + obj.get("client_review") + '">' +
'<option value="1" >Hate it!</option>' +
'<option value="2" >Don\'t love it but don\'t hate it.</option>' +
'<option value="3" >Fantastic!</option>' +
'</select>'
});​
function insertDropdown(td$, dropdownHTML) {
var dropdown$ = $(dropdownHTML);
dropdown$.val(dropdown$.data('value'));
td$.html(dropdown$);
}
for(var i = 0, l = tds.length; i < l; i++) {
insertDropdown($('#td-' + i), tds[i].content);
}
DEMO

Categories