giving id to the text field - javascript

I have a form at which 2 fields are generated by one drop down menu. Now the problem is I have generated one field and trying to get two fields, in first field price is shown and in second tag product_id is shown. My script is just showing price but not id. Due to lack of knowledge I am stuck. I just need help from someone.
JavaScript:
function setOptions(chosen) {
var selbox = document.myform.opttwo;
selbox.options.length = 0;
if (chosen == " ") {
selbox.options[selbox.options.length] = new Option('Please select one of the options above first',' '); }
selbox.options[selbox.options.length] = new Option('100 Directory Submission', '$9.99', '1');
selbox.options[selbox.options.length] = new Option('200 Directory Submission', '$19.99', '2');
selbox.options[selbox.options.length] = new Option('300 Directory Submission','$29.99', '3');
}
document.myform.amount.value="";
document.myform.hidden.value="";
}​
HTML:
<select name="opttwo" size="1" onchange="this.form.amount.value=this.value;">
<option value=" " selected="selected">Select any option of the above first</option>
</select>
Amount Payable:<input type="text" readonly="readonly" name="amount" />
Product id:<input type="text" name="hidden" readonly="readonly" />

First off there are some obvious problems with your code such as closed and unclosed braces.
One example of that is on this line:
if (chosen == " ") {
selbox.options[selbox.options.length] = new Option('Please select one of the options above first',' '); }
Edit: this is not no longer the case.
Secondly, the Options object that you're trying to create does not have the "id" property that you're trying to get unfortunately.
So your code
selbox.options[selbox.options.length] = new Option('100 Directory Submission', '$9.99', '1');
is not getting '1' as its id.
The constructor is
new Option([text], [value], [defaultSelected], [selected])
You can however get the index of an element by doing this in your onchange handler:
this.form.hidden.value=this.selectedIndex;
Thirdly, if you wanna continue on the path of using script in your onchange tags, which generally is discouraged, you have to set the value of the hidden input as well.
Like this:
onchange="this.form.amount.value=this.value; this.form.hidden.value=this.value;"
Note: this line above will give you the wrong value, just saying, but you get the gist of it.
I made a fiddle for you to toy around in and to see how it's done.
Here is it
Some API documentation is always in order I believe:
Update:
In order to set the id dynamically on every Option you have to loop over the elements in the select list like this:
for (var i=0; i<selbox.length; i++){
selbox.options[i].setAttribute('id', 'hello'+i);
}
Then in the line where you set in your onchange() you add this
this.form.hidden.value=this[selectedIndex].id;
Now your input should show, when you select an option, "hello0", "hello1", "hello2", "hello3".
Also, I updated the fiddle for you.
Mozilla Option API

Related

How to make dimanic input select option in chained dropdown option?

It's my first time i ask a question here. i'm stuck here, so i hope someone can solved this problem. thanks :)
I have some php code that i want to made a input select option adding automaticallly when clicked a button in my form. i mean, when the user clicked the button 3 times, so there are 3 input select options:
it was working when i have using with this javascript code:
var counter = 1;
var limit = 30;
function addInput(divName){
var kdprov= $("#provinsi_id").val();
if (counter == limit) {
alert("Maksimal input ialah " + counter + " sekolah");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<div><span class='input-group-addon' ><b> Sekolah ke-"+ (counter + 1)+"</span></b><select class='form-control' name='npsn"+
(counter + 1)+"' ><option value='' disabled selected>--Pilih Sekolah--</option>'.<?php foreach($sekolah as $sekolah1){ ?>'<option value='<?php echo $sekolah1->npsn;?>' ><?php echo $sekolah1->nama_sekolah; ?></option><?php } ?>.'</select></select></div>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
And this html code:
<input type="button" value="Tambah Sekolah" onClick="addInput('sekolah');"> </br></br>
but, the problem. they are retrieved all of variable $sekolah in database because i only used SELECT * FROM Sekolah in sql code.
And now I want to made a query SELECT * FROM Sekolah where provinsi=$provinsi
in my select option. but, the other problem is variable $provinsi got from javascricpt value. I mean,it is a chained dropdown. when i choose a option from $provinsi, so i want #sekolah option will retrieve only from the selected $provinsi option.
It worked in only static input, but i can't used it in my dimanic input select option.
So, what should i do? I'm not really understand about javascript, so can someone give me the solution? i made it in codeIgniter.
can i use a query in php code to get data from database in javascript?
Here is an example of how I would do this. I would create the select menu on load, so there is always one available. Then I would clone that select element whenever the button is clicked. See the example below.
Working example:
https://jsfiddle.net/tkfc031h/1
HTML
<div id="theSelectElements">
<label class="foo">Number <span>1</span>
<select>
<option>one</option>
<option>two</option>
<option>three</option>
<option>four</option>
<option>five</option>
</select>
</label>
</div>
<button id="addOne">One more</button>
jQuery
$('#addOne').click(function(){
var theSelect = $('.foo:last-child').clone();
var count = (parseInt(theSelect.find('span').text()) + 1);
theSelect.find('span').html(count);
theSelect.find('select').attr('name', "select"+count)
$('#theSelectElements').append(theSelect);
})
First of all, let me clarify what you want.
You have a dropdown "Provinsi" contains for example:
Aceh
Sumatera Utara
Riau & Kepri
And you have a button "Tambah Sekolah".
You select "Sumatera Utara" then click "Tambah Sekolah", you will have a new dropdown "Sekolah", contains for example:
sekolah sumut 1
sekolah sumut 2
sekolah sumut 3
You select "Riau & Kepri" then click "Tambah Sekolah", you will have another new dropdown "Sekolah", contains for example:
sekolah riau 1
sekolah riau 2
sekolah riau 3
If the above requirements is what you want, then you should use ajax too. Here what you need to do:
Collect the value of selected "province" by using javascript
Send "province" by using ajax to a page in server-side
A page in server-side, query the database for list of school filterd by "province" (SELECT * FROM sekolah WHERE provinsi = ?), then return the list of values to be shown in dropdown
After ajax request has been completed, create a new dropdown with values from previous ajax response
In this example: https://jsfiddle.net/o0s1L4k1/, see what happen if "Tambah Sekolah" button is clicked:
$.ajax({
method: 'POST',
url: 'list-sekolah.php', // page that will query schools by province
data: {
provinsi: $('#provinsi').val() // send currently selected province
},
success: function(response) {
// build the new <select> and append it
var html = $('<p>Sekolah: <select>' + response + '</select></p>');
$('body').append(html);
}
});

How to make a <option> default selected for a ajax-filled <select> with JQueryMobile?

I fill my <select> with the response from ajax call.
Here's the JS code:
var myOptions = {val1 : project1,
val2 : project1,
val4 : project1,
val5 : project1,
};
$.each(myOptions, function(val, text) {
$('#projectid').append(
$('<option ></option>').val(val).html(text)
);
});
my html code:
<input type="hidden" name="ehidden" value="true">
<select name="project" id="projectid"></select>
The required DropDown list I get is ok, but I can't set the first <option> to default selected.
Here's some code I already tried:
$('select.projectid').find('option[value="val1"]').prop('selected', true);
I got no error, but also no result. The same with this one:
$("#projectid").val($("#projectid option:first").val());
Second Problem:
the first <option> is not available the first time I select it per mouseclick, I have to first select the second <option> and then the first again.
Your selector is wrong on this line:
$('select.projectid').find('option[value="val1"]').prop('selected', true);
That is selecting a drop-down with a class of projectid. It should be:
$('#projectid').find('option[value="val1"]').prop('selected', true);
...which will select the element with an id of projectid.
Concerning this code:
$("#projectid").val($("#projectid option:first").val());
I'm not sure what you intended it to do, but it will select the first option in the drop-down. If no other option is selected, the first one is selected by default. So, if you were to run this code when the page loads, it of course would do nothing since the first option is already selected.
Concerning your "second" problem, you need to post that as a separate question as it's unrelated to this one. But, be sure to search for an answer to it here on SO before you pose it.
There are a few improvements you can make to your code that will make it simpler and allow you to easily mark the selected option. Here is a jsfiddle to solve your problem: jsfiddle
var myOptions = [
{ name: "A", value: "val1", selected: true},
{ name: "B", value: "val2"},
{ name: "C", value: "val3"},
{ name: "D", value: "val4"}
];
var optionsHtml = "";
for(var i = 0; i < myOptions.length; i++) {
var val = myOptions[i];
optionsHtml += '<option value = "' + val.value + '"';
if(val.selected)
optionsHtml += 'selected="' + val.selected + '"';
optionsHtml += '>' + val.name + '</option>';
}
$('#projectid').append(optionsHtml).selectmenu('refresh', true);;
Explanation
You will want to just build the html for your options and then appending to all the selects once. This will improve the performance of your code because you will only be appending once, thus causing the browser to do one redraw.
Doing it this way you can build the options as a string. I don't know how you determine which option to select but you should be able to change the if clause to suit your needs.
What you tried
$('select.projectid').find('option[value="val1"]').prop('selected', true);
This will not work because your selector is wrong. You are using the id as a class here you want:
$('#projectid')
$("#projectid").val($("#projectid option:first").val());
I'm not sure why this does not work. But you would not want to do it this way because it would be hard to select the option dynamically.
EDIT
To get the select in jQuery Mobile to update its selection you must call refresh. See the documentation here.

Set option of the Select box according to JSON result

I actually have some questions but I will start with the main one. I want to set the value of Select box on the basis of JSON.
Here's the HTML in question,
<label class="lbl">Office: </label>
<select tab-index="6" class="required" name="office" class="off">
<option value="">---------</option>
<option value="U">London</option>
<option selected="selected" value="R">Delhi</option>
<option value="W">Lisbon</option>
</select>
JSON sends it like this, I can't show the full JSON since it's too big, but I will show a part, Location: "U".
Here's the JS part:
if (data.Office === "R") {
$('select option[value="Delhi"]').prop('selected', true);
}
if (data.Office === "U") {
console.log('here');
$('.off option[value="London"]').attr('selected', 'selected');
}
if (data.Office === "W") {
$('select option[value="Lisbon"]').prop('selected', true);
}
But it's not working? Can any one point out why?
Moreover, I have a list of managers say and I am also getting that in JSON. So I am doing this,
for (var i = 0; i < data.Managers.length; i++) {
find_input = $('input[name="project_manager[]"').length;
if (find_input != data.Managers.length) {
$('<input type="text" name="project_manager[]" class="" value="" />').appendTo('#managers');
}
console.log(data.Managers[i].Manager);
$('input[name="project_manager[]"').each(function() {
$(this).val(data.Managers[i].Manager);
});
}
No of textboxes depend on the number of managers, but it only sets the value of last item from the array of managers in text boxes that are appended. Why?
Moreover I am not able to set value of textarea in Firefox like this:
$('textarea#some_id').val(data.Description);
It works in Chrome though.
First you need to add the character "<" in the beginning of the 3rd option of the select box:
<option selected="selected" value="R">Delhi</option>
Now, in the JS code, your problem is that you're using the wrong value. Instead of:
$('select option[value="Lisbon"]').prop('selected', true);
You must use:
$('select option[value="W"]').prop('selected', true);
I hope it help.
I think your selectors should be of the form:
$('select option[value="R"]').prop('selected', true);
Note the value is the same as the value in the HTML, not the displayed string (i.e. 'R' instead of 'Delhi').
Also, you should be using prop() consistently for selected flag, as described here by John Resig.

Javascript multiple select boxes

I tried searching for an answer to this for a while, but to no avail.
I'm trying to do a simple online calculator (that calculates some photovoltaic panels energy), but I'm stuck in something simple (I'm new to Javascript although I worked with Flash's ActionScript 3.0 for a while).
What I need done is a html select that defines which other select group appears in the page. Something like this (obviously this doesn't work, just setting an example):
HTML
<html>
<body>
<select id="test1" onclick="checkField()">
<option>Selected A Group</option>
<option>Selected B Group</option>
</select>
<script>//insert second group here</script>
</body>
</html>
Javascript
function checkField(){
var temp = document.getElementById('test1').value;
if(temp === "Selected A Group"){
//insert code to "echo" the first optional select group
} else {
//insert code to "echo" the second optional select group
}
}
Sorry if its a bit confusing, but I cant really explain all that well.
Here is an example of what I would want, where selecting a option makes the other fields change accordingly: http://www.toshiba.eu/innovation/download_drivers_bios.jsp
you are almost there, actually javascript doesn't "echo" values directly, it does log values using console.log(your value); to a debug console, similar to AS2 trace() if my memory isn't failing.
To "output" information to the document you should have a look into document.write
When you use document.write it will directly write to the documents end.
The "correct" way would be to create a DOM element, with the elements you want inside it, and then append it to the desired element. Have a look at the comments
<!-- Be Aware to use the onchange trigger on select boxes, if you use onclick the function will run, even
if you didn't really chose any option -->
<select id="test1" onchange="checkField()">
<!-- Is good to have a first non-value option, better to trigger the onchange event, if you have
Select A Group as first option and you click on it, it didn't really "Change", you would have to
pick B Group and then A Group again to trigger the onchange event correctly. -->
<option value="">-- select an option --</option>
<!-- You can have a value attribute on the options, so it's easy to process when programming
while displaying a more detailed description to the users -->
<option value="A">Selected A Group</option>
<option value="B">Selected B Group</option>
</select>
<!-- We create an empty element where we are gonna place the new Select -->
<div id="newSelect"></div>
<!-- By Placing the Javascript on the end of <body>, we ensure that all the DOM elements loaded before running the script -->
<script>
function checkField(){
var newSelect = document.getElementById('newSelect'); //targeting container;
var temp = document.getElementById('test1').value;
//Some tasks we do always the option chose is not the first custom one, so we don't have to repeat it
//on the two If's below
if(temp !== ""){
// We remove the select if we placed one already before, so we can add the new one,
// For example if we chose B Group but changed our mind and Chose A Group later.
if(oldChild = newSelect.getElementsByTagName('select')[0]){
oldChild.remove();
}
var select = document.createElement("select");
select.setAttribute('id', 'newSelect');
}
if(temp === "A"){
//you could do JUST:
//body.innerHTML = "all the html you want in here" instead of all the code following;
//but all those code is supposed to be the "correct way" of adding elements to the HTML,
//Google a bit about that for detailed explanations
var option1 = document.createElement("option");
option1.value = 1;
option1.text = "Option 1";
var option2 = document.createElement("option");
option1.value = 2;
option2.text = "Option 2";
select.appendChild(option1);
select.appendChild(option2);
newSelect.appendChild(select);
} else {
var option1 = document.createElement("option");
option1.value = 3;
option1.text = "Option 3";
var option2 = document.createElement("option");
option1.value = 4;
option2.text = "Option 4";
select.appendChild(option1);
select.appendChild(option2);
newSelect.appendChild(select);
}
}
</script>
Of course there are ways to make this slightly shorter, using loops if your data to ouput has a pattern, but lets do it the "simple" way so you get a grasp of Javascript.
Hope all this helped you!!
Demo here:
http://jsfiddle.net/3GkrX/
Just about the same as Mevins.... changed to switch/case though
html:
<select id="test1" id="name" onchange="checkField()">
<option>----</option>
<option>Selected A Group</option>
<option>Selected B Group</option>
</select>
<div id="optional">Please select!</div>
JS:
function checkField(){
var temp = document.getElementById('test1').value;
switch(temp){
case "Selected A Group":
document.getElementById("optional").innerHTML="<select name='optionalA'><option>1</option><option>2</option></select>";
break;
case "Selected B Group":
document.getElementById("optional").innerHTML="<select name='optionalB'><option>3</option><option>4</option></select>";
break
default:
document.getElementById("optional").innerHTML="Please select!";
break;
}
}
Also added the second group as a real option, and a default as "please select". may or may not be necessary in your case
Here is the demo http://codepen.io/anon/pen/izAHo
your doing it almost right.
You should put the onclick event on the option tag to trigger changes based on the option selected.
HTML
<html>
<body>
<select id="test1">
<option onclick="checkField()">Selected A Group</option>
<option>Selected B Group</option>
</select>
<select id="test2">
<option onclick="check2Field()">Selected C Group</option>
<option>Selected D Group</option>
</select>
<script>//insert second group here</script>
</body>
</html>
JS
function checkField(){
var temp = document.getElementById('test1').value;
if(temp === "Selected A Group"){
document.getElementById('test2').innerHTML="<option>Selected halloooo Group</option>";
} else {
//insert code to "echo" the second optional select group
}
}
Check out my demo for more clarity.

Dynamically Change Multiple Hidden Form Fields

I'm somewhat new to jQuery. I'm pretty sure this is possible, but I'm not quote certain how to code this.
What I'm looking to do is to use a dropdown with selections that represent ranges (e.g. if someone were searching for bedrooms, the dropdown selctions would look like "0-2", "3-5", "6+"). Then when someone chooses a selection, two hidden fields would by dynamically filled. One field with the minimum of the range, and the other field with the maximum of the range.
Here is an example of how I'm trying to structure this:
<select id="bedrooms" class="dropdown">
<option>Bedrooms</option>
<option></option>
<option value="1">0-2</option>
<option value="2">3-5</option>
<option value="3">6+</option>
</select>
<input type="hidden" name="bedrooms-from" value=''>
<input type="hidden" name="bedrooms-to" value=''>
I suppose the values of each option could change, I wasn't sure what the best way to approach that would be.
I haven't actually run this, but I think it should work:
$("#bedrooms").change(function ()
{
// Get a local reference to the JQuery-wrapped select and hidden field elements:
var sel = $(this);
var minValInput = $("input[name='bedrooms-from']");
var maxValInput = $("input[name='bedrooms-to']");
// Blank the values of the two hidden fields if appropriate:
if (sel.val() == "") {
minValInput.val("");
maxValInput.val("");
return;
}
// Get the selected option:
var opt = sel.children("[value='" + sel.val() + "']:first");
// Get the text of the selected option and split it on anything other than 0-9:
var values = opt.attr("text").split(/[^0-9]+/);
// Set the values to bedroom-from and bedroom-to:
minValInput.val(values[0]);
maxValInput.val((values[1] != "") ? values[1] : 99999999);
});
$("select").on("change", function() {
$("form").append( /* <input type='hidden'> tag here */ );
});

Categories

Resources