Copy text from text box onkeyinput to other textbox based on dropdown? - javascript

Good day.
I need to copy what's being typed into a textbox to multiple other text boxes.
The catch is that there is a dropdown which must determine this.
The process: User will enter a "Commodity" into the "Commodity" text box.
After this, they will then select from a dropdown the number of "Delivery Places". If they choose "1"; textbox "Commodity1" will have the same contents as the main "Commodity" textbox.
If they choose "2" as "DeliveryPlaces", both "Commodity1" & "Commodity2" will have the contents typed into "Commodity". This process should follow until "5" for "DeliveryPlaces".
The reason I want it done like this is that most of our clients will only order one type of commodity, even though it will be transported to multiple locations;
function copy(){
if (document.getElementById("DeliveryPlaces").value = "1")
{
document.getElementById("Commodity1").value=document.getElementById("Commodity").value;
}
else if (document.getElementById("DeliveryPlaces").value = "2")
{
document.getElementById("Commodity1").value=document.getElementById("Commodity").value;
document.getElementById("Commodity2").value=document.getElementById("Commodity").value;
}
else if (document.getElementById("DeliveryPlaces").value = "3")
{
document.getElementById("Commodity1").value=document.getElementById("Commodity").value;
document.getElementById("Commodity2").value=document.getElementById("Commodity").value;
document.getElementById("Commodity3").value=document.getElementById("Commodity").value;
}
else if (document.getElementById("DeliveryPlaces").value = "4")
{
document.getElementById("Commodity1").value=document.getElementById("Commodity").value;
document.getElementById("Commodity2").value=document.getElementById("Commodity").value;
document.getElementById("Commodity3").value=document.getElementById("Commodity").value;
document.getElementById("Commodity4").value=document.getElementById("Commodity").value;
}
else if (document.getElementById("DeliveryPlaces").value = "5")
{
document.getElementById("Commodity1").value=document.getElementById("Commodity").value;
document.getElementById("Commodity2").value=document.getElementById("Commodity").value;
document.getElementById("Commodity3").value=document.getElementById("Commodity").value;
document.getElementById("Commodity4").value=document.getElementById("Commodity").value;
document.getElementById("Commodity5").value=document.getElementById("Commodity").value;
}
else
{
document.getElementById("Commodity1").value="";
document.getElementById("Commodity2").value="";
document.getElementById("Commodity3").value="";
document.getElementById("Commodity4").value="";
document.getElementById("Commodity5").value="";
}
}
<p>
Commodity
</p><input type="textbox" id="Commodity" onkeyinput="copy();">
<p>
Commodity1
</p><input type="textbox" id="Commodity1">
<p>
Commodity2
</p><input type="textbox" id="Commodity2">
<p>
Commodity3
</p><input type="textbox" id="Commodity3">
<p>
Commodity4
</p><input type="textbox" id="Commodity4">
<p>
Commodity5
</p><input type="textbox" id="Commodity5">
<p>
Delivery Places
</p>
<select style="width:50px;" id="DeliveryPlaces">
<option value="-">-</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
so by filling it in automatically we save the user some time.
I managed to get it working without the if conditions, that was simple enough. Now, however, it's only filling in "Commodity1" even though I choose a "DeliveryPlace" which IS NOT "1".
Any help would be appreciated.

Switch:
if (document.getElementById("DeliveryPlaces").value = "1")
to
if (document.getElementById("DeliveryPlaces").value == "1")
The code is actually switching DeliveryPlaces to 1 in your statement

Try using:
var e = document.getElementById("DeliveryPlaces")
var selection = e.options[e.selectedIndex].value;
Then do your condition based on the value in selection.
you are currently selecting the value of the Select element not the option you have actually selected.
Edit: it may be text rather than value you need on your selection, but give it a go!

I would do it like this:
function copy() {
var e = document.getElementById("DeliveryPlaces")
var selection = parseInt(e.options[e.selectedIndex].value);
var input = document.getElementById("Commodity").value;
var field;
for (var i = 1; i < 6; i++) {
field = "Commodity" + i;
if (i <= selection) {
document.getElementById(field).value = input;
} else {
document.getElementById(field).value = "";
}
}
}
This way, you can clear the other commodities, when you change to a lower delivery place + you can easily add more by editing the for loop.

Your function should receive the number of the dropdown. That is, if you selected 2 copy (2) so you can use a for and go through the ones you want to fill
for (i = item.length; i = 0; i--) {
document.getElementById("Commodity"+i).value=document.getElementById("Commodity").value;
}
The for will go from low to high until it reaches 0. that means that it will count if it is 5. 5,4,3,2,1 and will fill all the fields that you want. This avoids the amount of spaghetti code you have in your structure.
I understand that you are using pure javascript. But you could use jquery and it would make the job easier.

Related

Clear and re populate drop down list javascript

I want to set an alert every time this option (valList4) is clicked as well as automatically filling in the next text box. I want this to work even if after the first choice, another choice will still work.
I have this code:
$("#List4").change(function() {
var valList4 = $("#List4").val();
if (valList4 == "Ferrari")
{
$("#List5")[0].selectedIndex = 1;
fillSelect($("#List4").val(),$("#List5")[0]);
}
else if (valList4 == "Porsche")
{
$("#List5")[0].selectedIndex = 1;
fillSelect($("#List4").val(),$("#List5")[0]);
}
Here is the alert at the end of the code:
alert("Your selection was:- \n" + valList4);
});
The problem is that if I change my selection from one to the other, the list keeps populating and the second box will not change with the first box.
EDIT
Fill Select function
function fillSelect(currCat,currList){
var step = Number(currList.name.replace(/\D/g,""));
for (i=step; i<nLists+1; i++) {
document.forms['tripleplay']['List'+i].length = 1;
document.forms['tripleplay']['List'+i].selectedIndex = 0;
}
HTML Code
<form name="completion" action="">
<select id='List4' name='List4' onchange="fillSelect(this.value,this.form['List5'])">
<option selected>Make a selection</option>
</select>
<select id='List5' name='List5' onchange="getValue2(this.value, this.form['List4'].value,
this.form['List4'].value)">
<option selected >Make a selection</option>
</select></P>
</form>

Delete field based on selection change

Basically I'm not a coder I need an example of the proper code to accomplish this please. I am trying to make an electronic PTO form which I have linked within fiddle. What I want to do is if type1 changes then it deletes or subtracts anything in hours1 and really preferably in what ever total field the type1 has filled. So if you go to fiddle select Sick and type 8 in the hours field it will auto count in the total hours for sick onchange. However what if someone selects sick and really meant to select vacation currently they have to manually delete and re-enter all the numbers. I would like to automate the whole thing. I really appreciate your wisdom on this.
Here is the selection fields there are multiple.
<select name="type1" id="type1">
<option value="">Please Select</option>
<option value="Sick">Sick</option>
<option value="Vacation">Vacation</option>
<option value="Holiday">Holiday</option>
<option value="Floating Holiday">Floating Holiday</option>
<option value="Jury Duty">Jury Duty</option>
<option value="Bereavement">Bereavement</option>
<option value="Suspension Paid">Suspension Paid</option>
<option value="Suspension Unpaid">Suspension Unpaid</option>
</select>
This is where the employee enters in the hours of sick or whatever.
<input onchange="javascript:process()" name="hours1" class"hours1" type="text" id="hours1" size="4" maxlength="2" />
When they do this it automatically adds the hours together using the
Sick
<input name="totsick" type="text" id="totsick" size="4" maxlength="2" />
Vacation
<input name="totvac" type="text" id="totvac" size="4" maxlength="2" />
jsfiddle demo
Basically, you should recalculate all the numbers on each change of the type selects, and hours inputs.
that way you avoid miscalculations and lots of unnecessary logic.
here is an example FIDDLE
new code:
//this clause runs after DOM is loaded
$(function(){
//attach a onchange handler to all the type selects and hours texts easily
$("select[id^='type']").change(function(){
processTHREE();
});
$("input[id^='hours']").change(function(){
processTHREE();
});
});
function processTHREE() {
//reset all totals
$("#totsick").val("0");
$("#totvac").val("0");
$("#tothol").val("0");
$("#totfl").val("0");
$("#totjd").val("0");
$("#totber").val("0");
$("#totsp").val("0");
$("#totsu").val("0");
//get a list of all selects whose id starts with the word 'type'
var _types = $("select[id^='type']");
//iterate through them and check values
//the id/value here are the id of the select, and the select itself, not his selected value
$.each(_types, function (_idx, _value) {
var current_select = _types[_idx];
//gets the value of the selected option in the current select
var Selected_value = $("option:selected", current_select).val();
//get the corresponding hours value, parent().parent() goes up twice
//from the select, which means ->td->tr and in the same row search for
//hours input
var selected_hours = $("input[id^='hours']",$(current_select).parent().parent()).val();
//check the value and add to relevant field
if (Selected_value == "Sick") {
addTo("totsick",selected_hours);
} else if (Selected_value == "Vacation") {
addTo("totvac",selected_hours);
} else if (Selected_value == "Holiday") {
addTo("tothol",selected_hours);
} else if (Selected_value == "Floating Holiday") {
addTo("totfl",selected_hours);
} else if (Selected_value == "Jury Duty") {
addTo("totjd",selected_hours);
} else if (Selected_value == "Bereavement") {
addTo("totber",selected_hours);
} else if (Selected_value == "Suspension Paid") {
addTo("totsp",selected_hours);
} else if (Selected_value == "Suspension Unpaid") {
addTo("totsu",selected_hours);
}
});
}
function addTo(elId,hours) {
var element = document.getElementById(elId);
var current = element.value;
//alert(current+"/"+add);
// + before for integer conversion
element.value = +current + +hours;
}

Trying to create a drop-down of form fields, that is based on a number

Good afternoon!
I am building a contact form in Contact Form 7 in Wordpress. And I need a functionality where one of the form fields is a number selector (for example, 1-10) and I need the number that is selected to be calculated and drop down the number of fields to be inputted.
I'll try to explain the best I can. So if someone types in the 4...I need a drop down of four input fields.
I have looked for some jquery script for this functionality, but I'm basically at a deadend. If anyone has any suggestions, I would much appreciate it!
Here's an option using jQuery (jsFiddle)
HTML
Number of inputs:
<select class="numInputs" onChange="buildInputs(this);">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<div class="inputs"></div>
Javascript (jQuery)
$(document).ready(function () {
// set onchange event for the select box.
$('.numInputs').change(function () {
// clear any inputs added to the div.
$('.inputs').empty();
// get number of inputs to add from select box.
var num = $('.numInputs option:selected').text();
// build the inputs.
for (var i = 1; i <= num; i++) {
$('<input type="text"/><br/>').appendTo('.inputs');
}
})
});
You would use javascript, I wrote a simple sample for you. I haven't ever worked with wordpress, but this just works on it's own, and I would think you should be able to just put it in.
Javascript
<script type="text/javascript">
function thing(){
var num = document.getElementById("number").value; //Get the number out of the number field
document.getElementById("select").innerHTML = ''; //Get rid of the placeholder, or the old ones
for (var i = 0; i < num; i++){
var newOpt = document.createElement('option');
newOpt.innerHTML = i; //It'll just have a dropdown for 0 to the number
newOpt.value = i;
document.getElementById("select").appendChild(newOpt);
}
}
</script>
HTML
<form>
Number: <input type="number" name="number" id="number" onblur="thing();">
<select id="select">
<option value="no">Enter a number first</option>
</select>
<input type="submit" value="Submit">
</form>
Also, instead of using onblur, you could use onkeyup or something. onblur is for when it loses focus.

Check if dropdown's selected option is not the first with JavaScript

Below are the options that I have in my HTML code:
<label id="subn">
<select name="subs" id="subs">
<option value="nothing">Choose a Subject</option>
<option value="General Question">General Question</option>
<option value="MemberShip Area">MemberShip Area</option>
<option value="Others">Others</option>
</select>
</label>
I want to create JavaScript code that will check whether the user selected an option other than the first one.
Here is what I tried:
if (document.getElementsByTagName('option') == "nothing"){
document.getElementById("subn").innerHTML = "Subject is Required!";
document.getElementById("subs").focus();
return false;
}
You can check like this if nothing is the first option (usually the case in my experience):
if (document.getElementById('subs').selectedIndex == 0){
To still compare based on the value, do this:
var sel = document.getElementById('subs');
if (sel.options[sel.selectedIndex].value == 'nothing') {
You may want to change your markup so the label is beside, like this:
<select name="subs" id="subs"></select><label id="subn" for="subs"></label>
Otherwise this part: .innerHTML = "Subject is Required!"; will erase your <select> :)
This should do it:
var index = document.your_form_name.subs.selectedIndex;
var value = document.your_form_name.subs.options[index].value;
if (value === "nothing"){
// your further code here.........
}
document.getElementsByTagName('option') gives a collection of all option elements in the document and "nothing" is a string. Comparing a collection to a string is quite useless.
Also setting document.getElementById("subn").innerHTML = "Subject is Required!"; will delete the select element, so document.getElementById("subs") wouldn't find anything any more.
If you just need to know if anything is selected check the selectedIndex property of the select element:
if (document.getElementById("subs").selectedIndex <= 0) {
// nothing is selected
}
EDIT: Changed > 0 to <= 0. I would assume that it should be checked if the user didn't select anything, too.

Search a dropdown

I have this HTML dropdown:
<form>
<input type="text" id="realtxt" onkeyup="searchSel()">
<select id="select" name="basic-combo" size="1">
<option value="2821">Something </option>
<option value="2825"> Something </option>
<option value="2842"> Something </option>
<option value="2843"> _Something </option>
<option value="15999"> _Something </option>
</select>
</form>
I need to search trough it using javascript.
This is what I have now:
function searchSel() {
var input=document.getElementById('realtxt').value.toLowerCase();
var output=document.getElementById('basic-combo').options;
for(var i=0;i<output.length;i++) {
var outputvalue = output[i].value;
var output = outputvalue.replace(/^(\s| )+|(\s| )+$/g,"");
if(output.indexOf(input)==0){
output[i].selected=true;
}
if(document.forms[0].realtxt.value==''){
output[0].selected=true;
}
}
}
The code doesn't work, and it's probably not the best.
Can anyone show me how I can search trough the dropdown items and when i hit enter find the one i want, and if i hit enter again give me the next result, using plain javascript?
Here's the fixed code. It searches for the first occurrence only:
function searchSel() {
var input = document.getElementById('realtxt').value;
var list = document.getElementById('select');
var listItems = list.options;
if(input === '')
{
listItems[0].selected = true;
return;
}
for(var i=0;i<list.length;i++) {
var val = list[i].value.toLowerCase();
if(val.indexOf(input) == 0) {
list.selectedIndex = i;
return;
}
}
}
You should not check for empty text outside the for loop.
Also, this code will do partial match i.e. if you type 'A', it will select the option 'Artikkelarkiv' option.
Right of the bat, your code won't work as you're selecting the dropdown wrong:
document.getElementById("basic-combo")
is wrong, as the id is select, while "basic-combo" is the name attribute.
And another thing to note, is that you have two variable named output. Even though they're in different scopes, it might become confusing.
For stuff like this, I'd suggest you use a JavaScript library like jQuery (http://jquery.com) to make DOM interaction easier and cross-browser compatible.
Then, you can select and traverse all the elements from your select like this:
$("#select").each(function() {
var $this = $(this); // Just a shortcut
var value = $this.val(); // The value of the option element
var content = $this.html(); // The text content of the option element
// Process as you wish
});

Categories