I'm trying to take multiple user inputs from an HTML document and then transfer that data into a table using Javascript. Numerical data will transfer without an issue but dropdown select menus have been showing up as undefined, I've tried many different solutions I've seen on questions here but none of them have yielded any results. Any help anyone can provide would be much appreciated. Here is the relevant code...
HTML
<form class="items" action="" method="post" name="items">
<ul>
<li>
<label>Paint:</label>
<select id="paintColour">
<option value="White" selected="selected">White</option>
<option value="Blue">Blue</option>
<option value="Beige">Beige</option>
<option value="Red">Red</option>
<option value="Yellow">Yellow</option>
</select>
<select id="paintType">
<option value="Gloss">Gloss</option>
<option value="Matte">Matte</option>
<option value="Emulsion">Emulsion</option>
</select>
<input type="number" name="quantity" value="0" size="2" id="paintVolume">
<input type="button" value="Add" id="addPaint" onclick="Javascript:addPaints()">
</li>
Javascript
function addPaints(){
var paintColour = document.getElementById("paintColour").selectedIndex;
var paintType = document.getElementById("paintType").selectedIndex;
var paintVolume = document.getElementById("paintVolume");
var tblPaint = document.getElementById("tblPaint");
var paintRowCount = tblPaint.rows.length;
var paintRow = tblPaint.insertRow(paintRowCount);
paintRow.insertCell(0).innerHTML = '<input type="button" value="Delete" onClick=deletePaint(this) ">';
paintRow.insertCell(1).innerHTML = paintColour.value;
paintRow.insertCell(2).innerHTML = paintType.value;
paintRow.insertCell(3).innerHTML = paintVolume.value;
}
function deletePaint(obj){
var index = obj.parentNode.parentNode.rowIndex;
var tblPaint = document.getElementById("tblPaint");
tblPaint.deleteRow(index);
}
Your problem with select is you are selecting index and then try to get value. Instead choose element and get value.
function addPaints(){
var paintColour = document.getElementById("paintColour");
var paintType = document.getElementById("paintType");
var paintVolume = document.getElementById("paintVolume");
var tblPaint = document.getElementById("tblPaint");
var paintRowCount = tblPaint.rows.length;
var paintRow = tblPaint.insertRow(paintRowCount);
paintRow.insertCell(0).innerHTML = '<input type="button" value="Delete" onClick=deletePaint(this) ">';
paintRow.insertCell(1).innerHTML = paintColour.value;
paintRow.insertCell(2).innerHTML = paintType.value;
paintRow.insertCell(3).innerHTML = paintVolume.value;
}
function deletePaint(obj){
var index = obj.parentNode.parentNode.rowIndex;
var tblPaint = document.getElementById("tblPaint");
tblPaint.deleteRow(index);
}
Related
Hello I am trying to get the value from a select tag, using javascript, that is generated within a razor view using C#.
This is the html where the select tag is generated:
<form id="asignRol" method="post">
<select name="users" id="userChange">
#foreach (var user in Model.UserAndRolesInfo)
{
<option value="#user.Username">#user.Username</option>
}
</select>
<select name="rol" id="roleChange">
#foreach (var rol in #Model.roleAvailability)
{
<option value="#rol.Name">#rol.Name</option>
}
</select>
<button type="button" id="submitButton" class="btn btn-primary">Asignar rol</button>
</form>
The html select tag is generated as expected:
HTML phot
In a different js file I am trying to get the values of the selected options:
var submitButton = document.getElementById("submitButton");
var userSelect = document.getElementById("userChange");
var userSelectValue = userSelect.options[userSelect.selectedIndex].value;
var roleSelect = document.getElementById("roleChange");
var roleSelectValue = roleSelect.value;
submitButton.addEventListener("click", function () {
console.log(userSelectValue);
console.log(roleSelectValue);
})
With the result of only getting the default value:
Result
I tried passing the event and event.preventdefault.
You need to get the value when the event occurs not before it. In your case event click.
var submitButton = document.getElementById("submitButton");
var userSelect = document.getElementById("userChange");
var roleSelect = document.getElementById("roleChange");
submitButton.addEventListener("click", function() {
var userSelectValue = userSelect.options[userSelect.selectedIndex].value;
var roleSelectValue = roleSelect.options[roleSelect.selectedIndex].value;
console.log(userSelectValue);
console.log(roleSelectValue);
})
<form id="asignRol" method="post">
<select name="users" id="userChange">
<option value="#user.Username">#user.Username</option>
<option value="moses">moses</option>
<option value="cat">cat</option>
<option value="dog">dog</option>
</select>
<select name="rol" id="roleChange">
<option value="#rol.Name">#rol.Name</option>
<option value="mouse">mouse</option>
<option value="elephant">elephant</option>
<option value="fox">fox</option>
</select>
<button type="button" id="submitButton" class="btn btn-primary">Asignar rol</button>
</form>
So, I'm trying to make a JS action where it should display the selected items from the list, I can only select one but I want to select more than one and view it in a list
<body>
<label for="issue">Issue Type:</label>
<select multiple="multiple" name="issue" id="issue">
<option value="passport">passport</option>
<option value="selfie">selfie</option>
<option value="nationalId">nationalId</option>
</select>
<p> you are missing the following information:</p>
<ul id="issue-type">
<script>
var output = '';
let issues = document.getElementById("issue");
for (i = 0; i < issues.length; i++) {
output += document.write("<li>" + issues[i].text + </li>").innerHTML = issues;
}
</script>
</ul>
</body>
You need to use an event listener to listen for a change of selection and you need to update the html of the element. You rarely ever want to use document.write in an application.
const issueSelect = document.getElementById("issue");
// listen for a change
issueSelect.addEventListener("change", selChanged);
function selChanged() {
var output = '';
let issues = issueSelect.options;
// loop over the options
for (var i = 0; i < issues.length; i++) {
// is it selected?
if (issues[i].selected) {
// yes, build a list item
output += "<li>" + issues[i].value + "</li>";
}
}
// set the list's content
document.getElementById("issue-type").innerHTML = output;
}
<body>
<label for="issue">Issue Type:</label>
<select multiple="multiple" name="issue" id="issue">
<option value="passport">passport</option>
<option value="selfie">selfie</option>
<option value="nationalId">nationalId</option>
</select>
<p> you are missing the following information:</p>
<ul id="issue-type">
</ul>
</body>
How I would have coded it
const issueSelect = document.getElementById("issue");
// listen for a change
issueSelect.addEventListener("change", selChanged);
function selChanged() {
const selectedOpts = issueSelect.querySelectorAll("option:checked");
const output = [...selectedOpts].map(opt => `<li>${opt.value}</li>`).join('');
document.getElementById("issue-type").innerHTML = output;
}
<body>
<label for="issue">Issue Type:</label>
<select multiple="multiple" name="issue" id="issue">
<option value="passport">passport</option>
<option value="selfie">selfie</option>
<option value="nationalId">nationalId</option>
</select>
<p> you are missing the following information:</p>
<ul id="issue-type">
</ul>
</body>
Here is one solution and I commented each line.
let output = '';
let issues = document.querySelector("#issue");
let issue_types = document.querySelector("#issue-type");
issues.addEventListener("change", function(e) { //change event listener to check for when the select is changed
issue_types.innerHTML = ""; //empties destination div
let options = e.target.selectedOptions; //grabs the selected options
options = Array.from(options).map(({ value }) => value); //converts the selected options to an array of values
options.forEach(function(opt){ //loops through the options
let li = document.createElement("li"); //creates a LI element
li.innerHTML = opt; //sets the innerHTML of the list item to the option
issue_types.appendChild(li) //appends the list to the destination UL
});
});
<label for="issue">Issue Type:</label>
<select multiple="multiple" name="issue" id="issue">
<option value="passport">passport</option>
<option value="selfie">selfie</option>
<option value="nationalId">nationalId</option>
</select>
<p> you are missing the following information:</p>
<ul id="issue-type">
</ul>
I am looking to dynamically change the values of price and id with select of different drop downs in following anchor link. like If I select 3 days, the price changes to 24 in anchor and id with new oID.
Note: hidden fields are for data to submit in database. $_post['deadline']. Yes, correcting url. Type error.
<a class="btn btn-warning" href="https://example.com?price=38&id=DS123">order</a>
HTML
<div class="col-sm-6">
<label for="price" class="control-lable">Urgency*:</label>
<select class="form-control" name="price" id="price" onchange="func()" required>
<option value="">Select urgency</option>
<option value="24">3 Days</option>
<option value="38">5 Days</option>
<option value="62">7 Days</option>
</select>
</div>
<input type="hidden" name="deadline" id="deadline" value="" />
<input type="hidden" name="oid" id="oid" value="" />
Javascript
function func() {
var option = $("#price").val();
var dLine = $('#deadline').val();
var mID = new Date().getTime();
var oID = 'Q'+Math.round(mID/1000)
if (option =='24') {
dLine = 3 Days;
oID;
}
if (option =='38') {
dLine = 5 Days;
oID;
}
if (option =='62') {
dLine = 7 Days;
oID;
}
};
You have unnecessary hidden fields in HTML as well as unnecessary if conditions in jQuery(because i am unable to see and fruitfull use of those in your scenario)
Do it like below:-
function func() {
var option = $("#price").val();
var mID = new Date().getTime();
var oID = 'Q'+Math.round(mID/1000)
$('.btn-warning').attr('href',"https://example.com?price="+option+"&id="+oID)
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-6">
<label for="price" class="control-lable">Urgency*:</label>
<select class="form-control" name="price" id="price" onchange="func()" required>
<option value="">Select urgency</option>
<option value="24">3 Days</option>
<option value="38">5 Days</option>
<option value="62">7 Days</option>
</select>
</div>
<a class="btn btn-warning" href="https://example.com?price=38&id=DS123">order</a>
<!-- not required <input type="hidden" name="deadline" id="deadline" value="" />
<input type="hidden" name="oid" id="oid" value="" />-->
Note:-
Url:- https://example.com&price=38&id=DS123 seems in-correct as it need to be https://example.com?price=38&id=DS123 (check query-string notation ? there)
You can put an id in the anchor like:
<a id="btn-order" class="btn btn-warning" href="#">order</a>
Then in your onchange function (func), do something like:
$('#btn-order').attr('href', 'https://example.com?price=' + option + '&id=' + oID);
rather than using onchange=func(), you can try to keep it clean by using jquery .on() :
$('#price').on('change', function(e){
var $thisSelect = $(this),
$anchor = $('.btn.btn-warning'),
oID = 'Q'+Math.round((new Date().getTime())/1000),
newhref = 'https://example.com/?id='+oID+'&price='+$thisSelect.val(),
selectedText = $thisSelect.find('option:selected').text();
$anchor.prop('href', newhref);
$('#deadline').val(selectedText);
$('#oid').val(oID);
});
Vanilla js version:
function func () {
var e = document.getElementById("price");
var price = e.options[e.selectedIndex].value;
var button = document.getElementsByClassName('btn btn-warning')[0];
if (price && button) {
var mID = new Date().getTime();
var oID = 'Q'+Math.round(mID/1000);
button.setAttribute('href', "https://example.com?price=" + price + "&id=" + oID)
}
}
I have an understanding or css and html, but I'm quite new to JavaScript...
So, I have a div that has two functions. (var selection = a[selection].innerHTML;) is where the problem is, and I'm trying to get (bread)(milk)(cheese)
My HTML
function PP_BUDGET_CLIENT_TB_ACCOUNT_NUMBER_SEARCHDIV_MOUSEDOWN() {
//disable div
var PP_BUDGET_CLIENT_TB_ACCOUNT_NUMBER_SEARCHDIV = document.getElementById('PP_BUDGET_CLIENT_TB_ACCOUNT_NUMBER_SEARCHDIV');
var a = PP_BUDGET_CLIENT_TB_ACCOUNT_NUMBER_SEARCHDIV.getElementsByTagName("a");
var selection = a[selection].innerHTML;
console.log("select = " + selection);
document.getElementById('PP_BUDGET_CLIENT_TB_ACCOUNT_NUMBER').value = selection;
PP_BUDGET_CLIENT_TB_ACCOUNT_NUMBER_SEARCHDIV.style.cssText = 'display: none;';
}
<input type="text" class="CAPTURE_TB" placeholder="ACCOUNT NUMBER" id="PP_BUDGET_CLIENT_TB_ACCOUNT_NUMBER">
<div id="PP_BUDGET_CLIENT_TB_ACCOUNT_NUMBER_SEARCHDIV" class="CAPTURE_SEARCH" style="display:none;">
CHEESE
MILK
BREAD
</div>
In the HTML, I'm pulling the page with...
<script>
require('./UniWindow.js')
</script>
Inside 'UniWindow.js':
//PP_BUDGET_CLIENT_CONTROLLS
var PP_BUDGET_CLIENT_TB_ACCOUNT_NUMBER = document.getElementById('PP_BUDGET_CLIENT_TB_ACCOUNT_NUMBER');
//divs
var PP_BUDGET_CLIENT_TB_ACCOUNT_NUMBER_SEARCHDIV = document.getElementById('PP_BUDGET_CLIENT_TB_ACCOUNT_NUMBER_SEARCHDIV');
//PP_BUDGET_CLIENT_EVENTS
PP_BUDGET_CLIENT_TB_ACCOUNT_NUMBER.addEventListener('keyup', PP_BUDGET_CLIENT_TB_ACCOUNT_NUMBER_ONKEYUP);
PP_BUDGET_CLIENT_TB_ACCOUNT_NUMBER_SEARCHDIV.addEventListener('mousedown', PP_BUDGET_CLIENT_TB_ACCOUNT_NUMBER_SEARCHDIV_MOUSEDOWN)
//PP_BUDGET_CLIENT_FUNCTIONS
so #chrisG suggested
<input list="browsers" name="browser">
<datalist id="browsers">
<option value="Internet Explorer">
<option value="Firefox">
<option value="Chrome">
<option value="Opera">
<option value="Safari">
</datalist>
but electron does not support this feature. so I have created my own but if anyone could help even if i can somehow pass the variable to the method in the background.
You need to create function that assign some variable or just set you div value to text of selection and bind that function to each option onClick.
<input type="text" class="CAPTURE_TB" placeholder="ACCOUNT NUMBER" id="PP_BUDGET_CLIENT_TB_ACCOUNT_NUMBER">
<div id="PP_BUDGET_CLIENT_TB_ACCOUNT_NUMBER_SEARCHDIV" class="CAPTURE_SEARCH" style="display:block;">
<a name="test" href="#CHEESE" >CHEESE</a>
<a name="test" href="#MILK" >MILK</a>
<a name="test" href="#BREAD" >BREAD</a>
</div>
<script>
function Choose(){
document.getElementById('PP_BUDGET_CLIENT_TB_ACCOUNT_NUMBER').value = this.text;
}
var elements = document.getElementsByName("test");
for (var i = 0; i < elements.length; i++)
{
elements[i].addEventListener("click", Choose, false);
}
</script>
Possible duplicate of: setting content between div tags using javascript
Try this:
document.getElementById('PP_BUDGET_CLIENT_TB_ACCOUNT_NUMBER').innerHTML = selection;
This question already has answers here:
How not to refresh a page from JavaScript?
(3 answers)
Closed 6 years ago.
Please help me:
when i put this code it shows the result for only a sec before it refreshes the entire page. I havent been able to find any problems apart from it saying that calcCharterCost is not defined. I do not know what it means by that because to me it looks defined.
Thanks,
<script>
function calcCharterCost()
{
var destList = document.getElementById("destList");
var distance = destList.options[destList.selectedIndex].id;
var speedList = document.getElementById("speedList");
var gph = speedList.options[speedList.selectedIndex].id;
var speed = speedList.value;
var fuelCost = document.getElementById("fuelCost").value;
var feeOutput = document.getElementById("fee");
var time;
time = (distance / speed);
var cost;
cost = time * gph * fuelCost;
feeOutput.innerHTML = "$" + cost;
}
function validate()
{
if (isNaN(fuelCost) == true)
{
document.getElementById("error").innerHTML="Error invalid Fuel Cost";
document.myform.fuelCost.value="";
document.myform.fuelCost.focus();
}
}
</script>
<body>
<form name="myform">
<select id="destList">
<option id="28">Falmouth to Nantucket</option>
<option id="11">Falmouth to Edgartown</option>
<option id="7.6">Falmouth to Oak bluffs</option>
<option id="38">Falmouth to Newport</option>
</select>
<p/>
<select id="speedList">
<option id="18" value="14">14 kt</option>
<option id="24" value="18">18 kt</option>
<option id="30" value="20">20 kt</option>
<option id="37" value="22">22 kt</option>
</select>
<p/>
<input type="text" id="fuelCost" value="4.25" onblur="validate()"/>
<i><small><span style="color:red;" id="error" ></i></small> </span>
<p/>
<button onClick="calcCharterCost()">Calculate</button>
<p> The cost of the charter is <div id="fee">XXXX</div>
</body>
By default a button without a type will submit a form.
Either give the button a non-submit type:
<button type="button" onClick="calcCharterCost()">Calculate</button>
Or remove the form tag:
<form name="myform">
The latter seems preferable anyway, since the form tag is never closed and technically the markup is invalid. Nothing is actually using this form, so it's not needed.
You have markup errors and did not define fuelCost variable in global scope. When validate method executes, it cannot find the fuelCost variable as it is defined and used in calculate method.
I have fixed your script and markup issues. Please check out the corrected version and fiddle.
<script>
var fuelCost = 0;
function calcCharterCost() {
var destList = document.getElementById("destList");
var distance = destList.options[destList.selectedIndex].id;
var speedList = document.getElementById("speedList");
var gph = speedList.options[speedList.selectedIndex].id;
var speed = speedList.value;
fuelCost = document.getElementById("fuelCost").value;
var feeOutput = document.getElementById("fee");
var time;
time = (distance / speed);
var cost;
cost = time * gph * fuelCost;
feeOutput.innerHTML = "$" + cost;
}
function validate() {
if (isNaN(fuelCost) == true) {
document.getElementById("error").innerHTML = "Error invalid Fuel Cost";
document.myform.fuelCost.value = "";
document.myform.fuelCost.focus();
}
}
</script>
<body>
<select id="destList">
<option id="28">Falmouth to Nantucket</option>
<option id="11">Falmouth to Edgartown</option>
<option id="7.6">Falmouth to Oak bluffs</option>
<option id="38">Falmouth to Newport</option>
</select>
<p>
<select id="speedList">
<option id="18" value="14">14 kt</option>
<option id="24" value="18">18 kt</option>
<option id="30" value="20">20 kt</option>
<option id="37" value="22">22 kt</option>
</select>
</p>
<input type="text" id="fuelCost" value="4.25" onblur="validate()" />
<span style="color:red;" id="error"></span>
<button onClick="calcCharterCost()">Calculate</button>
The cost of the charter is
<div id="fee">XXXX</div>
</body>
Form tag is not needed in this scenario as it is not referenced by any other part of your code. I removed it.
Fiddle