Add to multiple select list with javascript from form - javascript

I'd like to have 2 blank input forms - category and value which when a button is pressed and they're appended/added to 2 multiple select forms, category and value. The data isn't being entered when the button is pressed.
function doAdd() {
// Pick up data from the category and value input fields;
// In my form these are named 'cat' and 'val'
var catstr = document.getElementById("cat").value;
var valstr = document.getElementById("val").value;
// pick up references to the text areas;
var cats = document.getElementById("catlist");
var nums = document.getElementById("numlist");
// Append text, inserting a new line character between
// data sets.
if (numadded > 0) {
cats.value = cats.value + "\n";
nums.value = nums.value + "\n";
}
numadded++;
cats.value = cats.value + catstr;
nums.value = nums.value + valstr;
}
HTML important lines
<script type="text/javascript" src="./checksubmit.js" ></script>
<input type="text" id="val" name="val" size="10"/>
<input type="text" id="cat" name="cat" size="30"/>
<input type="button" onclick="doAdd();" value="Add item">
<select multiple="multiple" id="catlist" style="width: 250px;"/>
<select multiple="multiple" id="numlist" style="width: 250px;"/>

I believe you want something like this
Demo fiddle
function doAdd() {
// Pick up data from the category and value input fields;
// In my form these are named 'cat' and 'val'
var catstr = document.getElementById("cat").value;
var valstr = document.getElementById("val").value;
// pick up references to the text areas;
var cats = document.getElementById("catlist");
var nums = document.getElementById("numlist");
//Create and append new options
var catOption = new Option(catstr, valstr);
var numOption = new Option(valstr, valstr);
cats.appendChild(catOption);
nums.appendChild(numOption);
}

Related

Display dropdown list text instead of value using innerhtml

I have a dropdown list with a function like this:
car_list.options[1] = new Option('Mazda', 'A_Mazda');
I put A_Mazda as the value of the dropdown for distinction. Now, I have a button which will display the dropdown list's values on a table view. What I want to display is text of the dropdown list and not the value. The function addRow() is what I did to display the dropdown list value in a table form. As for now, A_Mazda is displaying instead of Mazda when the button is cliked. Please help
function addRow(){
var table = document.getElementById("result-table");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML = car.value;
row.insertCell(1).innerHTML = model.value;
row.insertCell(2).innerHTML = '<input type="button" value="Delete" onClick="Javacsript:deleteRow(this)"/>';
}
function getDestination(){
var model_list = document.getElementById('model');
var car_list = document.getElementById("destination");
var list1SelectedValue = model_list.options[model_list.selectedIndex].value;
if (list1SelectedValue=='Cars')
{
car_list.options.length=0;
car_list.options[0] = new Option('--SELECT A CAR--', '');
car_list.options[1] = new Option('Mazda', 'A_Mazda');
car_list.options[2] = new Option('Toyota', 'B_Toyota');
car_list.options[3] = new Option('Honda', 'C_Honda');
car_list.options[4] = new Option('Hyundai', 'D_Hyundai');
}
else if (list1SelectedValue=='Food')
{
destination_list.options.length=0;
destination_list.options[0] = new Option('--SELECT A FOOD--', '');
destination_list.options[1] = new Option('Burger', 'A_Burger');
destination_list.options[2] = new Option('Fries', 'B_Fries');
destination_list.options[3] = new Option('Pasta', 'C_Pasta');
destination_list.options[4] = new Option('Ice cream', 'D_Ice_cream');
}
}
<h4>MODEL</h4>
<select class="form-control" id='model' name='model' onClick="getDestination()">
<option value = "Cars">Cars</option>
<option value = "Food">Food</option>
</select>
<h4>Car</h4>
<select class="form-control" id='destination' name='destination' onClick="getCriteria()" >
</select>
<input type= "button" id= "add" value="Add Destination" onclick= "Javascript:addRow()">
</td>
Use the .text property of the option, not .value, eg
row.insertCell(0).innerText = car.options[car.selectedIndex].text
Assuming car and model represent <option> elements, instead of car.value and model.value try to use the text attribute:
car.text
model.text

Don't append if string already contains OnChange

I have a javascript OnChange function on a column having textboxes which captures the name of each row in a column. I am appending all the names and storing in variable.
Now , suppose user clicks same textbox again , I don't want to append that name again.
var AppendedString = null;
function onChangeTest(textbox) {
AppendedString = AppendedString;
AppendedString = AppendedString + ';' + textbox.name;
// this gives null;txt_2_4;txt_2_6;txt_3_4;txt_2_4 and so on..and I don't want to append same name again , here it's txt_2_4
}
My Input text :
<input type="text" name="txt_<%=l_profileid %>_<%=l_processstepsequence%>" value="<%= l_comments%>" onfocus="this.oldvalue = this.value;" onchange="onChangeTest(this);this.oldvalue = this.value;">
Those rows seem to have unique names.
you can simply check if AppendedString already contains that name :
var AppendedString=''
function onChangeTest(textbox) {
if (!AppendedString.includes(textbox.name)) {
AppendedString += ';' + textbox.name;
}
}
Codepen Link
You can’t initialize AppendedString as null otherwise, the includes() method won’t be available
otherwise, you can give each row a unique ID, and store in an array IDs that already have been clicked by the user.
var AppendedString = '';
var clickedRows = [];
function onChangeTest(textbox) {
if (!clickedRows.includes(textbox.id)) {
AppendedString += ';' + textbox.name;
clickedRows.push(textbox.id)
}
}
var arr = [];
$("input[type='text']").on("click", function() {
var nowS = ($(this).attr('name'));
if (!(arr.indexOf(nowS) > -1)) {
arr.push(nowS)
}
console.log(arr)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="m1" name="lbl1">
<input type="text" id="m2" name="lbl2">
<input type="text" id="m3" name="lbl3">
Somewhat similar to your need,
var arr = [];
$("input[type='text']").on("click", function() {
var nowS = ($(this).attr('name'));
if (!arr.includes(nowS)) {
arr.push(nowS)
}
console.log(arr)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="m1" name="lbl1">
<input type="text" id="m2" name="lbl2">
<input type="text" id="m3" name="lbl3">
You can add flag your textboxes and ignore if it's clicked again. Like using jquery you can do something like this:
function onChangeTest(textbox) {
AppendedString = AppendedString;
if (!textbox.hasClass("clicked")){
AppendedString = AppendedString + ';' + textbox.name;
textbox.AddClass("clicked");
}
}

Setting values to fields with the same name/key possible?

Ok, say I have a checkbox such as this:
<input type="checkbox" value="1" class="discount_select" name="select[101132]">
...and 3 text fields like this:
<input type="text" name="start[101132]">
<input type="text" name="end[101132]">
<input type="text" name="discount[101132]">
I am running some code right now that will update the text field values if the checkbox is checked, however I'm not sure if or how you can target the correct fields as they all have different ID's.
So I basically have this code to loop through the checked boxes, but not sure how to make updates to the correct text fields:
// Get values
var discount = $('#apply_discount').val();
var start = $('#apply_start_date').val();
var end = $('#apply_end_date').val();
$('.discount_select:checked').each(function() {
// How can I target the correct fields/ID's here?
});
Try
// Get values
var discount = $('#apply_discount').val();
var start = $('#apply_start_date').val();
var end = $('#apply_end_date').val();
$('.discount_select:checked').each(function() {
var num = this.name.substring(7, this.name.length - 1);
$('input[name="start[' + num + ']"]').val(start)
$('input[name="end[' + num + ']"]').val(end)
$('input[name="discount[' + num + ']"]').val(discount)
});
Change the name and ids of your fields to make it simpler
<input type="checkbox" value="1" class="discount_select" id="101132" name="select_101132">
<input type="text" name="start_101132">
<input type="text" name="end_101132">
<input type="text" name="discount_101132">
Then:
var discount = $('#apply_discount').val();
var start = $('#apply_start_date').val();
var end = $('#apply_end_date').val();
$('.discount_select:checked').each(function() {
var select_id = this.attr("id");
$('[name=start_'+select_id+']').val(start);
$('[name=end_'+select_id+']').val(end);
$('[name=discount_'+select_id+']').val(discount);
});

How to process onchange events for select elements which is dynamically created using javascript?

I have to create a few "select" elements in a html file dynamically.
And I also intend to create the same amount "select" elements according to the value of
the former created "select" elements.
Thus I will have a set of "select" elements pair.
When the first "select" element's selected value is changed,
the second "select" elements will refresh its options using the according records in a database.
My problem is I can't receive the correct value of the first "select" element.
Everytime when the onchange event is called, the value passed on to onchange function( in my case, it's called "fillSource()" is the value before the change happened instead of the changed selected value.
Do anyone know how to solve this problem?
The following is my javascript code:
<script>
var selectCount = 1;
var cats = #{dropCatsJson};
var subcats = #{dropSourceJson};
function addNewSource() {
var inputchange = document.createElement('select');
inputchange.options[0] = new Option("pls Select", "0");
inputchange.id="schange";
var input1 = document.createElement('select');
for( var i=0;i< cats.length;i++ ) {
var s = cats[i];
input1.options.add( new Option(s.Name, s.Id) );
}
input1.id = 's' + selectCount;
//input1.onchange = new Function("alert(\"input1 changed\")");
input1.onchange = new Function("fillSource(" + input1.value + ")");
document.getElementById('newSource').appendChild(input1);
document.getElementById('newSource').appendChild(inputchange);
selectCount = selectCount + 1;
}
function fillSource(input1)
{
var dropsub = document.getElementById("schange");
dropsub.options.length = 0;//clear all the options.
for( var i=0;i< subcats.length;i++ ) {
var s = subcats[i];
if( s.ParentId == input1.value )
{
dropsub.options.add( new Option(s.Name, s.Id) );
}
}
}
</script>
===============================================================================
final code that works.
Please notice that you should add onchange event for newly created
select elements like this:
input1.onchange = function(){fillsource(input1.value)};
here is my test.html code:
<html>
<script type="text/javascript">
var selectCount = 1;
function addNewSearch()
{
//alert("add");
var input1 = document.createElement('select');
input1.options[0] = new Option("s1","1");
input1.options[1] = new Option("s2","2");
input1.name = 's' + selectCount;
input1.id = 's' + selectCount;
input1.onchange = function(){fillsource(input1.value)};
document.body.appendChild(input1);
selectCount = selectCount +1;
//alert(selectCount);
var selcount = document.getElementById('selCount');
selcount.textContent = selectCount;
}
function fillsource(ivalue)
{
alert(ivalue);
}
</script>
<form name= "Search" id= "SearchForm" method= "post">
<select name= "SearchWhat" onchange = "setSearchField()">
<option value = "both"> Both Event and Task </option>
<option value = "event"> Event </option>
<option value = "task" > Task </option>
</select>
<label id="selCount"></label>
<input type="submit" value= "submit" name = "btn_submit"/>
<input type="button" name= "newsearch" value= "New Search" onClick= "addNewSearch()">
</html>
You're capturing the value at the time you create the select element, and hard-coding it into the onchange function. You need to use a closure:
input1.onchange = (function(input1) {fillsource(input1.value)})(input1);

dropdown selection will not work with text only numbers used in JS for calculation of total

I have a form that only captures following fields.(see below) I need to revise it, so that field "formdesc" (form description) captures what was selected in the dropdown as text only. But now there is an options id = [0, 1, 2,3] that are used for price point in JS to calculate total ammount purchased.
HTML:
<form action="http://" method="get" name="form">
<input id="forminv" type="hidden" name="forminv" value="StudentOrg"> (fixed value)
<input id="formbal" type="hidden" name="formbal" value="0"> (this pulls total from id=tot)
<input type="text" name="formfname"> (this pulls first name)
<input type="text" name="formlname"> (this pulls last name)
<type="text" name="formid"> (this for a student number)
<select id="apparelType" name="formdesc"> (this should pull value from selection)
<option selected value="na">Select</option>
<option value="0">T-Shirt</option> (I need to change this value to “shirt”)
<option value="1">Shorts</option> (here too, but can't work with JS below)
<option value="2">Hat</option> (here too)
<option value="3">Bag</option> (here too)
<input id="numb" type="number" name="formterm"> (this pulls quantity, and changes total)
<id="tot"<Total: $0.00 >
<input type="submit" value=" Make a Credit Card Payment">
</form>
JS:
$(document).ready(function () {
$('#numb').keyup(function () {
var appVal = new Array();
appVal[0] = 15; (if I change this, stops working)
appVal[1] = 20;
appVal[2] = 25;
appVal[3] = 30;
var cost = 0;
var fmapVal = $('#apparelType').val();
if (fmapVal == 'na') {
alert('Please select an apparel type.');
} else {
cost = appVal[fmapVal];
};
//alert(cost);
var getNumb = $('#numb').val();
var baseTotal = cost * getNumb;
var getTax = baseTotal * .06;
var getTotal = baseTotal + getTax;
$('#tot').html('Total: $' + etTotal.toFixed(2));
$('#formbal').val(getTotal.toFixed(2));
});
});
Here is working fiddle
change $('#tot').html() to $('#tot').val()
If you require the selected items text, then use;
var txt = $('#apparelType').find('option:selected').text();

Categories