I've typed the whole calculation. I have a submission button which by clicking needs to retrieve the sum. It doesn't work. I'm pretty new at JavaScript so I can't really tell where is the problem. Here is the code:
$('#home_price').submit(function(){
var shutter_price, lights_price, socket_price, screen10_price, screen7_price, dimmer_price, x
var total_price = 3000;
shutter_price = ($('#shutter').val())*200;
light_price = ($('#lights').val())*200;
socket_price = ($('#socket').val())*200;
screen10_price = ($('#screen10').val())*700;
screen7_price = ($('#screen7').val())*200;
dimmer_price = ($('#dimmer').val())*400;
if($('#boiler').is(":checked")==true){
total_price+=600;
x+=1;
}
x+=($('#shutter').val())*2+($('#lights').val())+($('#socket').val());
Math.floor(x);
x+=1;
total_price = total_price + shutter_price + light_price + socket_price + screen10_price + screen7_price + dimmer_price + x*400;
$('#home_pricing').val()=total_price;
if($('#home_pricing').val() < 6000)
alert('the solution invalid');
else
alert(" total: " + $('#home_pricing').val());
});
});
and a piece of the html code:
<label for="screen7"> 7inch screen </label>
<input style="margin-right:70px" name="screen7" type="number" id="screen7"> <br><br>
<label for="dimmer"> dimmer</label>
<input style="margin-right:174px" name="dimmer" type="number" id="dimmer"> <br><br>
<label for="boiler"> bolier </label>
<input style="margin-right:148px" type="checkbox" name="boiler" id="boiler" > <br><br>
<div>
<input type="submit" name=" home_pricing " id="home_pricing" value=" calculate " >
</div>
</form>
I tried doing the same with document.getelementbyid(' one_of the id's').value
but still once I pick values in each input line and then click the submission button it just jumps to the window again with no values and doesn't print anything.
Change the submit button's type from 'submit' to 'button'. That way, clicking submit won't redirect you. What you have to do to set the values though, is make an onclick event for the new button.
Instead of using $('#home_price').submit(), use calculate() and it will work.
The default behavior when a form is submitted to is to to go to a new page. If no new page is specified, the current page is just reloaded. You can prevent that default behavior in the submit event handler method by invoking the event's preventDefault method. To do that, specify an event parameter to the submit method definition, then call preventDefault, like so:
$('#home_price').submit(function(event) {
event.preventDefault();
// Rest of your code here
// ...
Update
There are also a couple of obvious errors in your code. The Math.floor method does not modify the variable passed to it, it returns a integer value. Change this line:
Math.floor(x);
to this
x = Math.floor(x);
Putting the jQuery val() method on the left side of an assignment does do anything. However, you can pass a value to val() and it will set the new value. Change this line:
$('#home_pricing').val()=total_price;
to this:
$('#home_pricing').val(total_price);
Related
I have an input form which looks like this:
<input type="number" value="0.00" step="0.05">
I found the step function which technically solves my increment problem changing it to 0.05 instead of the default 1. I have however not found a solution where I can change the increment without changing the valid inputs.
The input can take any number but the most common values will be in increments of 0.05. Is there a work-around for this? A solution using JavaScript is also more than welcome.
Thank you very much!
EDIT:
Adding nonvalidateto the html form-tag solved this for me. Now pressing the buttons use the increments I want but when I need to specify more accurately than the steps the form still accepts the values.
<form action="/run" novalidate>
<input type="number" value="0.00" step="0.05">
<input type="submit">
</form>
Using novalidate in the form tag will get rid of the validation for the whole form but keep the increments implemented by step.
Update
"I did add nonvalidate to the form tag. It let's me do what I want as of now but it might not be the best solution."
If you don't want your form "compromised" by novalidate, then have 2 forms:
Form A [No action or method]
All user interaction and calculations are here.
All inputs can be modified without worrying about built-in validation from the form.
Form B [Set action and method optional target]
The submit button resides within
Add a hidden input for each value on Form A you want to submit and ensure each has a name attribute and value.
Any client-side validation should be done here.
With that setup you'll need an event like onbeforesubmit so the values of Form A can transfer over to Form B before it submits to the server. Unfortunately I don't think it exist as a standard, but to emulate it is simple:
formA.onsubmit = b4Submit;
function b4Submit(event) {
hidden_Input_In_FormA.value = number_Input_With_Crazy_Step_In_FormA.value
return true;
}
So this contrived example shows an event handler that gets the value from one form then stores it in the other form. Next it continues by submitting whatever data it has. This is due to the callback returning true, should false be returned, the callback function itself dies and so does the submit event along with it.
The Demo has been updated to do what was just described above. Note: there are no novalidate attributes in use. The second form (Form B or form#tx) is sending text from a hidden input as far as it's concerned. A number like -103.002684109 is not valid if it's from an <input type='number'> but from a text or hidden input, it is just text (although I believe the actual data in most form controls is actually a string not a number).
"The input can take any number but the most common values will be in increments of 0.05. Is there a work-around for this? A solution using JavaScript is also more than welcome."
You can change any attribute you want on any tag AFAIK. Programatically the syntax is simple with Plain JavaScript:
Object.property = "string"
Object: a referenced <element> tag
property: when you reference an standard attribute like a property it's becomes a property.
string: the value must be a string
Here's a basic way of changing a standard attribute programmatically:
var obj = document.querySelector('a');
obj.href = "https://google.com"; //
The following Demo uses:
Document.Forms
HTMLFormElement.elements
HTMLFormControlsCollection
Dot Notation
Demo
Demo can send to a live test server the response is sent to an iframe to view
var ui = document.forms.ui;
var tx = document.forms.tx;
var u = ui.elements;
var x = tx.elements;
var D = u.digit;
var C = x.cache;
var lo = u.min;
var hi = u.max;
var inc = u.step; // I think this what you specificly
var t = u.type;
var chg = u.change;
chg.onclick = chgAttr;
tx.onsubmit = cacheVal;
function chgAttr(e) {
D.min = lo.value;
D.max = hi.value;
D.step = inc.value;
D.type = t.value;
}
function cacheVal(e) {
C.value = D.value;
return true;
}
body {
font: 400 16px/1.5 'Consolas'
}
#digit {
margin-right: 15px;
}
input,
output,
button,
select,
option,
label {
display: inline-block;
font: inherit
}
select {
padding: 3px 5px
}
[type='submit'] {
float: right;
}
<!doctype html>
<html>
<head>
<title></title>
<meta charset='utf-8'>
<style></style>
</head>
<body>
<form id='ui' oninput='out.value = digit.value'>
<fieldset>
<legend>Click Button to Change Input</legend>
<input id='digit' min='' max='' step='' type='number'>
<button id='change' type='button'>CHANGE</button>
<output id='out' for='digit'></output>
</fieldset>
<fieldset>
<legend>Attribute Adjustments</legend>
<input id='min' min='-2147483648' max='2147483648' type='number' placeholder='min'>
<input id='max' min='-2147483648' max='2147483648' type='number' placeholder='max'>
<input id='step' type='number' placeholder='step'>
<label for='type'>Type:
<select id='type'>
<option>number</option>
<option>text</option>
<option>range</option>
<option>hidden</option>
<option>color</option>
<option>time</option>
</select>
</label>
</fieldset>
</form>
<form id='tx' action='https://httpbin.org/post' method='post' target='response'>
<input id='cache' name='cache' type='hidden'>
<input type='submit'>
</form>
<iframe src='about:blank' name='response'></iframe>
<script></script>
</body>
</html>
I THINK i have managed to write a script. I just can not make a textfield in HMTL to enter the missing data. It it supposed to receive the keyword from a text field on submit click and navigate to the URL.
I have tried multiple ways of forms and everything. Should have installed VB.net and this would have been done in 5 min.
function urlMaker(keyword) {
var base = "https://www.example.com/list.php?q=";
var ending = "&dhd=1&hdd=low&dtt=list";
var url;
url = base + keyword + ending;
window.location.assign(url);
}
In short words:
I need to know how to create a HTML page with a textfield and a submit button. When I submit it takes the text from the field and run the function and feeds it with the keyword from the textfield. When function has ran it redirects browser.
I'm guessing you have a form like this.
Just attach a submit event-listener to it:
document.querySelector("#search").addEventListener("submit", urlMaker)
function urlMaker(event) {
let keyword = document.querySelector("#keyword").value;
let base = "https://www.example.com/list.php?q=";
let ending = "&dhd=1&hdd=low&dtt=list";
let url;
event.preventDefault();
url = base + keyword + ending;
window.location.href = url;
}
<form id="search">
<input type="text" id="keyword" />
<button type="submit">Search</button>
</form>
I have a textbox. I wanted to use a JS onclick to append the input in the textbox to the "btnGO" button as below but it's not working:
document.getElementById('btnGo').onclick = function() {
var search = document.getElementById('dlrNum').value;
window.location.url = "http://consumerlending/app/indirect/dealerComments.aspx?dlrNum=" + search;
}
<input id="dlrNum" type="text" name="dlrNum" autocompletetype="disabled" class="ui-autocomplete-input" autocomplete="off">
<input id="btnGo" type="submit" value="GO" name="GO" runat="server">
What could I be missing?
You had several problems there:
1. Your <input> elements are probably part of a form, so when you click on the submit button - the form will submit, unless you prevent it.
2. You need to use window.location.href (and not .url).
Here is the fix to your code:
document.getElementById('btnGo').onclick = function(e) {
e.preventDefault()
var search = document.getElementById('dlrNum').value;
window.location.href = "http://consumerlending/app/indirect/dealerComments.aspx?dlrNum=" + search;
}
Note the e element inside the function(e) - it's there so we can use the event object to prevent the default behavior of the form submission.
Update window.location.url to window.location:
window.location = "http://consumerlending/app/indirect/dealerComments.aspx?dlrNum=" + search;
I'd like to be able to find the number value of the courseAmount input field upon submit, and then generate new input fields (into the hourForm form underneath the initialForm) through the onsubmit method in javascript, and then retrieve the value from each of the generated input fields upon the submission of the hourForm form and place those values into an array.
However, I'm having difficulty with actually generating the input fields with javascript, and I suspect that I'm having difficulty with retrieving the value of the courseAmount input and porting that to my createInput() function, but I'm not exactly sure if that's the issue.
Here's my HTML:
<!DOCTYPE html>
<head>
<link rel="stylesheet" href="css/main.css">
</head>
<body>
<form id="initialForm" method="post" onsubmit="createInput()" action="">
<label>Number of hours for which you would like to study</label>
<input type="number" name="overallHours" id="overallHours" class="stored" min="1" max="20" step="1" value="1"/>
<label>Number of courses you would like to study for</label>
<input type="number" name="courseAmount" id="courseAmount" class="stored" min="1" max="20" step="1" value="1"/>
<input type="submit" class="submitStudy" value="Submit"/>
</form>
<form id="hourForm" method="post" onsubmit="calcHours">
<label>State the desired time spent working in each course</label>
</form>
</body>
And here's my Javascript:
var notedOverallHours = document.getElementById("overallHours").value * 60;
var courseNumberTotal = document.getElementById("courseAmount").value;
var counter = 0;
function createInput() {
var newForm = document.getElementById("hourForm");
document.getElementById("initialForm").style.display = "none";
document.getElementById("hourForm").style.display = "block";
for (i = 0; i <= courseNumberTotal; i++) {
newForm.innerHTML = "<label>Course #" + (counter + 1) + "</label>" + "<input type='number' name='courseHours' class='newInputs' min='1' max='9' step='1' value='1'/>";
counter++;
}
newForm.innerHTML = "<input type='submit' value='submit'/>";
}
Can someone help me figure this Javascript out? My JSFiddle attempts have been futile because JSFiddle does not take kindly to forms reloading the page.
Thank you!
From the mdn page about innerHTML: "Removes all of element's children, parses the content string and assigns the resulting nodes as children of the element." https://developer.mozilla.org/en-US/docs/Web/API/Element.innerHTML
Generally speaking you do not want to use innerHTML at all. There is almost always a better approach. In this case this will be createElement and appendChild.
Furthermore, there is no such thing as "onsubmit" method. What you are calling like that is an HTML attribute which registers a handler for the submit event. http://www.quirksmode.org/js/introevents.html
However using html attributes has its serious drawbacks: http://www.quirksmode.org/js/events_advanced.html
Considering all that, here is what I would do: http://jsfiddle.net/ashnur/rwod4z1d/
HTML:
<form id="initialForm" method="post" action="">
<label>Number of hours for which you would like to study</label>
<input type="number" name="overallHours" id="overallHours" class="stored" min="1" max="20" step="1" value="1" /><hr>
<label>Number of courses you would like to study for</label>
<input type="number" name="courseAmount" id="courseAmount" class="stored" min="1" max="20" step="1" value="1" /><hr>
<input type="submit" class="submitStudy" value="Submit" />
</form>
<form id="hourForm" method="post" >
<label>State the desired time spent working in each course</label><hr>
</form>
js:
var notedOverallHours = document.getElementById("overallHours").value * 60;
var courseNumberTotal = document.getElementById("courseAmount").value;
var counter = 0;
var initialForm = document.getElementById("initialForm");
var hourForm = document.getElementById("hourForm");
initialForm.addEventListener('submit', createInput);
hourForm.addEventListener('submit', calcHours);
function calcHours() {}
function createInput(ev) {
ev.preventDefault(); // this is not needed if you are using a bare button and the click event
var newForm = document.getElementById("hourForm");
initialForm.style.display = "none";
hourForm.style.display = "block";
for (i = 0; i <= courseNumberTotal; i++) {
addControl(newForm, "Course #" + (counter + 1));
counter++;
}
var submit = document.createElement('input');
submit.type = 'submit';
submit.value = 'submit';
newForm.appendChild(submit);
}
function addControl(form, labelText) {
var label = document.createElement('label');
var input = document.createElement('input');
var hr = document.createElement('hr');
input.type = 'number';
input.name = 'courseHours';
input.classname = 'newInputs';
input.min = '1';
input.max = '9';
input.step = '1';
input.value = '1';
label.textContent = labelText;
form.appendChild(label);
form.appendChild(input);
form.appendChild(hr);
}
As Tobias correctly pointed out, your form submission event is allowed to continue which results in a page refresh and a "reset" of all plain JavaScript data. Furthermore, you are not capturing your values (notedOverallHours and courseNumberTotal) on form submission (after the user has entered an amount), but rather when your page initializes (before the user has input anything).
So, to go about fixing this, first a tiny modification to your HTML:
...
<form id="initialForm" method="post" action="">
...
Notice that I deleted the onsubmit attribute from your form. We can capture that with an event in JavaScript itself.
Next attach an event listener to your form which prevents it from submitting and calls your createInput() function:
document.getElementById("initialForm").addEventListener('submit', function (e) {
e.preventDefault();
createInput();
});
This will attach an eventListener that listens to the submit event on your initialForm element. The first parameter is the type of event you want to listen for (submit in this case), the second is the callback you want to have fired.
The callback function always gets the event passed in (the e argument). By calling preventDefault on this event we can stop it from bubbling up and actually causing a page refresh.
Next we call the createInput() function which, after some modifications, looks like this:
function createInput() {
var notedOverallHours = document.getElementById("overallHours").value * 60;
var courseNumberTotal = document.getElementById("courseAmount").value;
var newForm = document.getElementById("hourForm");
document.getElementById("initialForm").style.display = "none";
document.getElementById("hourForm").style.display = "block";
// Add our elements
for (i = 1; i <= courseNumberTotal; i++) {
var child = document.createElement('li');
child.innerHTML = "<label>Course #" + (i) + "</label>" + "<input type='number' name='courseHours-"+ i+"' class='newInputs' min='1' max='9' step='1' value='1'/>";
newForm.appendChild(child);
}
// Add our button
var button = document.createElement('li');
button.innerHTML = "<input type='submit' value='submit'/>";
newForm.appendChild(button);
}
As you can see, I capture the notedOverallHours and courseNumberTotal variables inside the createInput() function, so they will carry whichever value was set during the form submission event.
Then we iterate over each course number. Instead of replacing the innerHTML, we first create an element (li in our case) and fill that element with a HTML string. Next we append this child element to the parent form.
Inside the loop I have removed the counter variable as you can simply use the value of i inside the loop, no need to create an extra variable. I also appended the name attribute for each child with i, so not to get any name clashes.
At the end of our function we simply create and append a new li element containing the submit button.
You can optimize this further by actually creating the label and input elements with the createElement function and set its attributes and text individually with plain JavaScript setters, instead of dumping everything inside li elements as I've done here to keeps things a bit more simple for now. I`ll leave that up as an exercise :)
I have created a rough JSFiddle with this exact code here.
When the createInput() function is called you are not having the desired results because you are reseting the newForm.innerHTML in each iteration of the loop and then again at the end. Rather than using = you should be using += to append the desired text rather than replace the existing text.
// Replacing the contents of newForm.innerHTML
newForm.innerHTML = "foo";
// Appending to newForm.innderHTML (You want to do this)
newForm.innerHTML += "foo";
Another problem is that when you press submit the page is reloading before createInput() is able to have the desired result. You most likely want to stop the page actually submitting and thus reloading when you press the submit button. To do this you can change the onsubmit attribute for the form to "return createInput()" and then add the line return false; to the end of the createInput() function to indicate to the browser that you do not wish to submit the form.
I have this input field in html:
<input id="title" type="text" class="" />
A button will allow the user to randomize the value of the input field by calling a js function.
var title = document.getElementById("title");
title.removeAttribute("value");
title.setAttribute("value",random_name);
If the user wants to change the value auto-asigned by my function (aka random_name), he can simply type something else in the input field.
All works fine until now, however if the user changes his mind and clicks the randomize button again, the function is called and "value" attribute is modified, but the user still sees the last thing he typed and not the new random value.
Is there a way to fix this or maybe a workaround?
Just do title.value = random_name
You can set an input's value by element.value = "desired_value". If you use that, it works.
http://jsfiddle.net/f4gVR/2/
<input id="title" type="text" class="" />
<input type="button" class="" onclick="randomValue()" value="Random" />
function randomValue() {
var title = document.getElementById("title");
title.value = Math.random(); // assign random_name to title.value here
}
if it's your random_name bugging out, you should post the code. Try this first. Just replace Math.random() with random_name.
you need to use title.value = random_name; instead of title.setAttribute("value",random_name);
Fiddle: http://jsfiddle.net/4dhKa/