Submit function when the same form is on the page twice - javascript

I have the below JavaScript submit function for a form that works fine. But when the form is on the page twice it only works for the first form and not for the second. I presume I need to use something with this so it only works on the active form?
HTML:
<form action="resultsnew.php" method="get" style="margin-bottom: 0" class="store-search-form">
<input type="text" name="d" value="Enter Postcode..." onclick="this.value='';" onfocus="this.select()" onblur="this.value=!this.value?'Enter Postcode...':this.value;" class="find-form-input field store-search-postcode" />
<input type="submit" onclick="java" value="Search" class="button" />
</form>
JavaScript:
$('.store-search-form').submit(function() {
//get the input's value
var postcodeinput = $('.store-search-postcode').val();
//remove spaces
postcodeinput = postcodeinput.replace(/\s/g, '');
//if valid postcode length trim it down
if (postcodeinput.length >= 5 && postcodeinput.length <= 7) {
//set the input's value
$('.store-search-postcode').val(postcodeinput.substring(0,postcodeinput.length - 3));
}
});

Do your searching relative to $(this) via find, i.e., change this:
var postcodeinput = $('.store-search-postcode').val();
to this:
var $this = $(this);
// ...
var postcodeinput = $this.find('.store-search-postcode').val();
(And in the other places you use it.)
Remember, within an event handler, this refers to the element the handler was hooked up to. $(this) creates a jQuery instance for that element. And then find searches within that element's descendants.

You need to reference the input that is in each form using $(this).find('.store-search-postcode') and then use that reference:
$('.store-search-form').submit(function() {
//get the input
var postcodeinput = $(this).find('.store-search-postcode');
//get the input's value
var postcode = postcodeinput.val();
//remove spaces
postcode = postcode.replace(/\s/g, '');
//if valid postcode length trim it down
if (postcode.length >= 5 && postcode.length <= 7) {
//set the input's value
postcodeinput.val(postcode.substring(0, postcode.length - 3));
}
});

Related

Javascript form value restriction

I am trying to create a form which will store values in an empty array but the values must be between 0 to 5 and comma separated. the problem is it alerts if values is more than 5 but still stores the value in the array. I want it to alert and then restore the form value.
Here is my code:
<form name ="form1" onsubmit="return validateForm()">
<input type="number" name="text" id="inputText" name="inputText" />
<button onclick="pushData();">Insert</button>
<p id="pText"></p>
</form>
And javascript:
function validateForm () {
var form = document.forms["form1"]["inputText"].value;
if(form <0 && form >= 6) {
alert('value should must be between 0 to 5');
return false;
}
}
// create an empty array
var myArr = [];
function pushData() {
// get value from the input text
var inputText = document.getElementById('inputText').value;
// append data to the array
myArr.push(inputText);
var pval = "";
for(i = 0; i < myArr.length; i++) {
pval = pval + myArr[i];
}
// display array data
document.getElementById('pText').innerHTML = "Grades: " + pval ;
}
Try
if (form <0 || form >= 6)
I think it may work better if you reorganize where the functions are being bound.
Event propagation order:
The button is clicked, and the value is pushed into the array.
The form's submit event triggers, and validates the values, but it's too late.
There are many ways to approach this one, but the simplest would be to call pushData at the end of your validateForm.
Adjusted the condition, because there's no way for a number to
be less than 0 AND greater than or equal to 6 at the same time.
Also added event.preventDefault to stop form submission.
JavaScript
function validateForm (event) {
event.preventDefault();
var form = document.forms["form1"]["inputText"].value;
if (form < 0 || form > 5) {
alert('value should must be between 0 to 5');
return false;
}
pushData();
}
HTML
<form name="form1" onsubmit="validateForm(event)">
<input type="number" id="inputText" />
<button type="submit">Insert</button>
<p id="pText"></p>
</form>
JSFiddle
Note that per the MDN:
A number input is considered valid when empty and when a single number
is entered, but is otherwise invalid.
With this particular form element you may add min and max attributes so that the user must enter a value within a specified range. Therefore, the current contents of the OP's validateForm() function are superfluous. Additionally, that function has a problematic line of code:
if(form <0 && form >= 6) {
You cannot have a value that is both less than zero and greater than or equal to six. Use instead a logical OR, i.e. "||" operator for the logic to work.
The following code allows for a user to select numeric values in the range that the OP specifies and then it displays them in a comma-separated format, as follows:
var d = document;
d.g = d.getElementById;
var pText = d.g('pText');
pText.innerHTML = "Grades: ";
var inputText = d.g("inputText");
var myArr = [];
function pushData() {
var notrailingcomma = "";
myArr.push(inputText.value);
if (myArr.length > 1) {
notrailingcomma = myArr.join(", ").trim().replace(/,$/g,"");
pText.innerHTML = "Grades: " + notrailingcomma;
}
else
{
pText.innerHTML += inputText.value;
}
}
d.forms["form1"].onsubmit = function(event) {
event.preventDefault();
pushData();
};
p {
padding: 1em;
margin:1em;
background:#eeeeff;
color: #009;
}
<form name="form1">
<input type="number" id="inputText" name="inputText" min=0 max=5 value=0>
<button type="submit">Insert</button>
</form>
<p id="pText"></p>
A couple of points with respect to the form:
The OP's HTML has an error in the input field: it has two names. I dropped the one with a name of "text".
I like what #thgaskell recommends with respect to changing "Insert" into a submit button, preventing the default action of submitting the form, and associating pushData with the form's onsubmit event. So, I've modified the code accordingly.

How to display rounded values in a form and show on focus the original values?

I have numeric values with many decimal places and the precision is required for other functions. I want to present the values in a form, so the user can change the values if necessary.
To increase the readability, I want to display the values rounded to 2 decimal places, but if the user clicks on an input field, the complete value should be presented. By doing this, the user can see the real value and adjust them better.
Example:
HTML
<button id="myBtn" onclick="fillForm()">Try it</button>
<form id="myForm" >
<fieldset>
<input type="text" id="myInput1" onchange="myFunction()" >
</fieldset>
</form>
JavasSript
<script>
//Example values that should be presented
var x = 3.14159265359;
function fillForm(){
document.getElementbyId("myInput1").value = x;
}
function myFunction(){
x = document.getElementbyId("myInput1");
}
</script>
The form input value should be " 3.14 " and if the user clicks in the field, the displayed value should be 3.14159265359.
Now the user can change the value and the new value has to be saved.
Because this is for a local 1 page website with no guaranty of internet connection, it would be an asset but not a requirement, to do it without an external script (jquery …).
you can use focus and blur event to mask/unmask you float, then simply store the original value in a data param, so you can use the same function to all input in your form ;)
function fillForm(inputId, val)
{
var element = document.querySelector('#'+inputId);
element.value = val;
mask(element);
}
function mask(element) {
element.setAttribute('data-unmasked',element.value);
element.value = parseFloat(element.value).toFixed(2);
}
function unmask(element) {
element.value = element.getAttribute('data-unmasked') || '';
}
<button onclick="fillForm('myInput1',3.156788)">Fill!</button>
<form id="myForm" >
<fieldset>
<input type="text" id="myInput1" onblur="mask(this)" onfocus="unmask(this)" >
</fieldset>
</form>
Edit: added "fillForm()" :)
Just use .toFixed(). It accepts one argument, an integer, and will display that many decimal points. Since Javascript primitives are immutable, your x variable will remain the same value. (also when getting/setting the value of an input use the .value property
function fillForm(){
document.getElementbyId("myInput1").value = x.toFixed(2);
}
If you need to save it you can store it in a new value
var displayX = x.toFixed(2)
Here is my solution. I hope you have other suggestions.
HTML
<form id="myForm" >
<fieldset>
<input type="text" id="myInput1" >
</fieldset>
</form>
<button id="myBtn" onclick="fill_form()">fill form</button>
JavasSript
<script>
var apple_pi = 10.574148541;
var id_form = document.getElementById("myForm");
//Event listener for form
id _form.addEventListener("focus", copy_input_placeh_to_val, true);
id _form.addEventListener("blur", round_input_2decimal, true);
id _form.addEventListener("change", copy_input_val_to_placeh, true);
// Replace input value with input placeholder value
function copy_input_placeh_to_val(event) {
event.target.value = event.target.placeholder;
}
// Rounds calling elemet value to 2 decimal places
function round_input_2decimal(event) {
var val = event.target.value
event.target.value = Number(val).toFixed(2);
}
// Replace input placeholder value with input value
function copy_input_val_to_placeh(event) {
event.target.placeholder = event.target.value;
}
// Fills input elements with value and placeholder value.
// While call of function input_id_str has to be a string ->
//fill_input_val_placeh("id", value) ;
function fill_input_val_placeh (input_id_str, val) {
var element_id = document.getElementById(input_id_str);
element_id.placeholder = val;
element_id.value = val.toFixed(2);
}
// Writes a value to a form input
function fill_form(){
fill_input_val_placeh("myInput1", apple_pi);
}
</script>
Here is an running example
https://www.w3schools.com/code/tryit.asp?filename=FLDAGSRT113G
Here is solution, I used focus and blur listeners without using jQuery.
I added an attribute to input named realData
document.getElementById("myInput1").addEventListener("focus", function() {
var realData = document.getElementById("myInput1").getAttribute("realData");
document.getElementById("myInput1").value = realData;
});
document.getElementById("myInput1").addEventListener("blur", function() {
var realData = Number(document.getElementById("myInput1").getAttribute("realData"));
document.getElementById("myInput1").value = realData.toFixed(2);
});
function fillForm(value) {
document.getElementById("myInput1").value = value.toFixed(2);
document.getElementById("myInput1").setAttribute("realData", value);
}
var x = 3.14159265359;
fillForm(x);
<button id="myBtn" onclick="fillForm()">Try it</button>
<form id="myForm" >
<fieldset>
<input type="text" id="myInput1" realData="" onchange="myFunction()" >
</fieldset>
</form>
jsfiddle : https://jsfiddle.net/mns0gp6L/1/
Actually there are some problems that needs to be fixed in your code:
You are redeclaring the x variable inside your myFunction function with var x =..., you just need to refer the already declared x without the var keyword.
Instead of using document.getElementById() in myFunction, pass this as a param in onchange="myFunction(this)" and get its value in the function.
Use parseFloat() to parse the value of your input to a float, and use .toFixed(2) to display it as 3.14.
This is the working code:
var x = 3.14159265359;
function fillForm() {
document.getElementById("myInput1").value = x.toFixed(2);
}
function myFunction(input) {
x = parseFloat(input.value);
}
To display the original number when you click on the input you need to use the onfocus event, take a look at the Demo.
Demo:
var x = 3.14159265359;
function fillForm() {
document.getElementById("myInput1").value = x.toFixed(2);
}
function focusIt(input){
input.value = x;
}
function myFunction(input) {
x = parseFloat(input.value);
}
<button id="myBtn" onclick="fillForm()">Try it</button>
<form id="myForm">
<fieldset>
<input type="text" id="myInput1" onchange="myFunction(this)" onfocus="focusIt(this)">
</fieldset>
</form>

Disable Button Until Fields are Full Pure JS

Trying to keep a button disabled until the form fields are filled in and I cannot seem to accomplish this. I've created a small example with a single field but the principle will be the same with a larger form.
Can anyone help?
Code:
function checkForm() {
var name = document.getElementById("name").value;
var cansubmit = true;
if (name.value.length == 0) {
cansubmit = false;
}
if (cansubmit == false) {
document.getElementById("submitbutton").disabled = true;
}
};
<input type="text" id="name" onkeyup="checkForm()" />
<button type="button" id="myButton">Test me</button>
There are a couple of mistakes in your sample:
var name is assigned to the value string of the name element, then you check the value property of that - the string has no value property.
the id of the submit button is myButton so use that id to get it by id (when setting the disabled attribute).
You can disable the submitbutton until the length of the name input is greater than 0.
And disabling the button initially sounds like a good idea, right?
See corrected example below:
function checkForm()
{
var name = document.getElementById("name").value;
var cansubmit = (name.length > 0);
document.getElementById("myButton").disabled = !cansubmit;
};
<input type="text" id="name" onkeyup="checkForm()" />
<button type="button" id="myButton" disabled="disabled">Test me</button>
You might also want to consider handling change via methods other than keypress - e.g. mouseup, etc... I tried adding onchange="checkForm()" and it works but only on blur (focus-change)...

Grabbing User Input

First name: <input type="text" name="firstname"></input>
<input type="submit" value="Submit" />
Let's say I have the simple form above. How would I grab what the user inputted in the First Name field in JS. I tried:
document.getElementsByTagName("input")[1].onclick = function() {
inputted = document.getElementsByTagName("input")[0].innerHTML;
}
But that doesn't work. How would I do this?
Use value for text inputs:
inputted = document.getElementsByTagName("input")[0].value;
Also make sure to add var keyword to your variables so that you don't create a global variable:
var inputted = document.getElementsByTagName("input")[0].value;
You should also not put closing </input> tag since it is self-closing tag:
<input type="text" name="firstname" />
By the way you can also get elements value using below syntax:
formName.elementName.value;
Or
document.forms['formName'].elementName.value;
In your case it would be:
var inputted = formName.firstname.value;
Or
var inputted = document.forms['formName'].firstname.value;
Replace formName with whatever name is of your <form> element.
Lastly you can also get element's value if you apply id to it:
<input type="text" name="firstname" id="firstname" />
and then use getElementById:
var inputted = document.getElementById('firstname');
var inputs=document.getElementsByTagName("input"),
i=inputs.length;
//
while(i--){
inputs[i].onclick=myClickEventHandler;
};
//
function myClickEventHandler(evt){
var myVal;
switch (this.name) {
case 'firstname':
myVal = this.value;
break;
};
};
If you are using a form, you could try something like this instead :
var input = document.forms["formName"]["fieldName"].value;
Else, make use of the .value attribute :
var input = document.getElementsByTagName("input")[0].value;

Fill data in input boxes automatically

I have four input boxes. If the user fills the first box and clicks a button then it should autofill the remaining input boxes with the value user input in the first box. Can it be done using javascript? Or I should say prefill the textboxes with the last data entered by the user?
On button click, call this function
function fillValuesInTextBoxes()
{
var text = document.getElementById("firsttextbox").value;
document.getElementById("secondtextbox").value = text;
document.getElementById("thirdtextbox").value = text;
document.getElementById("fourthtextbox").value = text;
}
Yes, it's possible. For example:
<form id="sampleForm">
<input type="text" id="fromInput" />
<input type="text" class="autofiller"/>
<input type="text" class="autofiller"/>
<input type="text" class="autofiller"/>
<input type="button"value="Fill" id="filler" >
<input type="button"value="Fill without jQuery" id="filler2" onClick="fillValuesNoJQuery()">
</form>
with the javascript
function fillValues() {
var value = $("#fromInput").val();
var fields= $(".autofiller");
fields.each(function (i) {
$(this).val(value);
});
}
$("#filler").click(fillValues);
assuming you have jQuery aviable.
You can see it working here: http://jsfiddle.net/ramsesoriginal/yYRkM/
Although I would like to note that you shouldn't include jQuery just for this functionality... if you already have it, it's great, but else just go with a:
fillValuesNoJQuery = function () {
var value = document.getElementById("fromInput").value;
var oForm = document.getElementById("sampleForm");
var i = 0;
while (el = oForm.elements[i++]) if (el.className == 'autofiller') el.value= value ;
}
You can see that in action too: http://jsfiddle.net/ramsesoriginal/yYRkM/
or if input:checkbox
document.getElementById("checkbox-identifier").checked=true; //or ="checked"

Categories

Resources