I want to keep the submit button disabled until the required fields are being filled.
Firstly ,
I found some questions about this issue but the problem was i have some required fields and not required fields also i am creating these fields dynamically.
Here is an example:
<input type="text" id="releaseartist" name="releaseartist" required="true" placeholder="Required Field"/>
Also i have input like that , this is how i am creating them dynamically,
var trackartistinput = document.createElement('input');
trackartistinput.setAttribute('type', "text");
trackartistinput.setAttribute('id', "trackartist" + i);
trackartistinput.setAttribute('name', "trackartist");
trackartistinput.setAttribute("required", true);
trackartistinput.setAttribute("placeholder", "Required Field");
trackartistinput.setAttribute("class", "required");
And this is my submit button :
<input type="submit" class="btn btn-primary" value="Submit" id="form-submit" onclick="return myConfirm();" />
you can check the count of required fields added in the document so far and based on the counts you can set the property of submit button to disabled or enabled.
you can count required class components as follow:
var numItems = $('.required').length
EDIT
to check if all the required class elements are filled you can check as follow:
var required_ele = document.getElementsByClassName('required');
var allfilled=true;
for (var i = 0; i < required_ele.length; ++i) {
var item = required_ele[i];
if(item.value.length==0){
allfilled=false;
}
}
if(allfilled){
document.getElementById("form-submit").disabled = false;
}
else{
document.getElementById("form-submit").disabled = true;
}
Start with button having disabled attribute set.
Add change event listener to form element (assuming that is the parent of all input
elements)
in change handler check if all required fields are filled, if yes, enable submit button
This work well even if user remove value entered in required field later, submit button will become disabled again
Related
I am trying to add error message handling in Javascript but am having trouble. If a user inputs a state that is not two characters in length, I am trying to have it output an error message. I also am including my renderBarChart function too if that helps.
js
stateSubmitButton.addEventListener("click", function(event) {
event.preventDefault();
state = stateUserInput.value.toUpperCase();
let stateFeedbackElem = document.querySelector("#stateFeedback");
if (state.length == 2) {
stateUserInput.setCustomValidity("");
stateFeedbackElem.textContent = "";
renderBarChart(state);
state = "";
} else {
stateUserInput.setCustomValidity("Please enter a two letter abbreviated state.");
stateFeedbackElem.textContent = "Please enter a two letter abbreviated state.";
state = "";
}
})
html
<form class="form" novalidate>
<label for="state-input">State:</label>
<input name="state" type="text" id="state-input" placeholder="(i.e. WA)">
<button type="submit" id="state-submit" class="btn btn-dark btn-lg ml-2">Submit</button>
<div id="stateFeedback" class="invalid-feedback"></div>
</form>
I noticed a couple of problems.
You have set novalidate on your form, which means .setCustomValidity() error will not be shown as validation will not be performed.
If the novalidate attribute is set on the <form> element, interactive
validation of the constraints doesn't happen.
-- Constraint validation
If stateUserInput is the #state-input input, .textContent should work, and the text should be set. But it is probably not shown as the invalid-feedback class has CSS property display: none;. You need to add a d-block class or use invalid-feedback element as shown in Bootstrap examples.
And just a note, prefer to add an event listener on the form and listen for the SubmitEvent instead of the click event on the submit button.
I have a form where I am calculating the total amount using jQuery.
The function I created for that is updateTotal();
and the form action is another page and the action page has this button:
<button class="btn btn-success" onclick="history.go(-1);" type="submit" name="edit">EDIT</button>
so when the user clicks on the EDIT button page goes back to the form again (first page) and all the filled up details are there except the repetitve fields created using jQuery.
The sample form is here in js fiddle
I just want to run this function updateTotal(); if the user comes to the form by clicking the EDIT (basically browse go back) button..
Is there any way to do this in jQuery?
UPDATES FOR FUTURE REFERENCE - I SOLVED IT LIKE THIS
html:
<input type="text" id="amount" name="amount[]" placeholder="Amount" required="required" class="form-control inputChangeVal reqF reqFamount" data-js-input-type="number" />
and the jQuery :
jQuery(document).ready(function() {
var hiddenTot = jQuery('.reqFamount').val() ;
jQuery(".totalAmount").val(hiddenTot);
});
Define a hidden field to store the computed value.
<input type="hidden" id="hiddenTotal" />
Then store the calculated value to the hidden field with Id 'hiddenTotal'.
function updateTotal() {
var price = 0;
$(".inputChangeVal").each(function() {
var t = parseFloat(jQuery(this).val(), 10);
price = price + t;
});
var total = price.toFixed(2);
$(".totalAmount").val(total);
$("#hiddenTotal").val(total);
}
Then when the browse back is triggered the hiddenfield is automatically filled by the browser.
Next check when the document is ready, read the value of hiddenTotal and write to totalAmount.
$(document).ready(function (){
// read value and set value of totalAmount to hiddentotal;
var hiddenTotal = $("#hiddenTotal").val() || 0; //use the hiddenTotal value or if not present set 0 as the default value
$(".totalAmount").val(hiddentotal)
}
Now totalAmount is restored. This even works when you leave the page and return using your browsers history.
I've read many blogs and posts on dynamically adding fieldsets, but they all give a very complicated answer. What I require is not that complicated.
My HTML Code:
<input type="text" name="member" value="">Number of members: (max. 10)<br />
Fill Details
So, a user will enter an integer value (I'm checking the validation using javascript) in the input field. And on clicking the Fill Details link, corresponding number of input fields will appear for him to enter. I want to achieve this using javascript.
I'm not a pro in javascript. I was thinking how can I retrieve the integer filled in by the user in input field through the link and displaying corresponding number of input fields.
You could use an onclick event handler in order to get the input value for the text field. Make sure you give the field an unique id attribute so you can refer to it safely through document.getElementById():
If you want to dynamically add elements, you should have a container where to place them. For instance, a <div id="container">. Create new elements by means of document.createElement(), and use appendChild() to append each of them to the container. You might be interested in outputting a meaningful name attribute (e.g. name="member"+i for each of the dynamically generated <input>s if they are to be submitted in a form.
Notice you could also create <br/> elements with document.createElement('br'). If you want to just output some text, you can use document.createTextNode() instead.
Also, if you want to clear the container every time it is about to be populated, you could use hasChildNodes() and removeChild() together.
<html>
<head>
<script type='text/javascript'>
function addFields(){
// Generate a dynamic number of inputs
var number = document.getElementById("member").value;
// Get the element where the inputs will be added to
var container = document.getElementById("container");
// Remove every children it had before
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i=0;i<number;i++){
// Append a node with a random text
container.appendChild(document.createTextNode("Member " + (i+1)));
// Create an <input> element, set its type and name attributes
var input = document.createElement("input");
input.type = "text";
input.name = "member" + i;
container.appendChild(input);
// Append a line break
container.appendChild(document.createElement("br"));
}
}
</script>
</head>
<body>
<input type="text" id="member" name="member" value="">Number of members: (max. 10)<br />
Fill Details
<div id="container"/>
</body>
</html>
See a working sample in this JSFiddle.
Try this JQuery code to dynamically include form, field, and delete/remove behavior:
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".container1");
var add_button = $(".add_form_field");
var x = 1;
$(add_button).click(function(e) {
e.preventDefault();
if (x < max_fields) {
x++;
$(wrapper).append('<div><input type="text" name="mytext[]"/>Delete</div>'); //add input box
} else {
alert('You Reached the limits')
}
});
$(wrapper).on("click", ".delete", function(e) {
e.preventDefault();
$(this).parent('div').remove();
x--;
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container1">
<button class="add_form_field">Add New Field
<span style="font-size:16px; font-weight:bold;">+ </span>
</button>
<div><input type="text" name="mytext[]"></div>
</div>
I am trying to change the value of a hidden field on submission by JavaScript. In my page there are two buttons, one for going back to homepage (index.php) and another for returning to the first page for data entry (addData.php). I am trying to use a hidden field with id "goHome" to control the routeing. My codes are like this:
HTML (Form only)
<form name = "addDataReal" id = "addDataReal" method = "POST" action = "addDataProc.php" onsubmit="return checkNSub()">
<!-- Other items -->
<input type = "submit" name = "submitBtnF" id = "submitBtnF" class="shortText" style = "width: 120px;" value = "Submit + Home" onclick = "return getGoValue(true)"/>
<input type = "submit" name = "submitBtnR" id = "submitBtnT" class="shortText" style = "width: 120px;" value = "Submit + Next" onclick = "return getGoValue(false)"/>
<input type = "hidden" name = "goHome" id = "goHome" value = "" />
</div>
</form>
Javascript
function checkNSub() {
//form validation functions
//OK then return true
//Not then return false
}
function getGoValue(goHome) {
if (goHome) {
document.getElementById("goHome").value = "true";
} else {
document.getElementById("goHome").value = "false";
}
return true;
}
Before this I have tried many other versions and I refered to these few questions:
Set form hidden value on submit
Setting a form variable value before submitting
How to change the value of hidden input field before submitting
But none of the methods were working for me.
For practical purposes there is a workaround for this, but I want to know if I would like to keep these two buttons, how should my code be modified so that the value of "goHome" can be changed before the form is submitted? After many attempts I am still getting $_POST["goHome"] = "".
Also, why is the form submitted before the value is actually changed when the code is placed before that?
Thanks!
It's old question But I thought If any one still looking for the answer , here it is
You can try jquery $('input[name="goHome"]').val('true');
or JS - document.getElementByName("goHome").value = "true";
This will work for sure.
While updating any value at the time of submitting for use name selector instead of ID, that will save you some time :)
When we try to change value of Hidden field at the time of submitting form it didn't update value because DOM has already detached the ID from the input parameter but name is still there because name is going to be passed in form.
If anyone find this useful and they do not have to work for lot hours for a simple solution :)
Happy Coding :)
Various ways to achieve this. Firstly though keep in mind that you are using type="submit" <input> inside a <form> , and that means that they will automatically submit the form regardless of an onclick event or not.
One as much as less intrusive (to your code) way is the following:
Take out the submit inputs from your form like this:
Example :
<form name = "addDataReal" id = "addDataReal" method = "POST" action = "whatever.php">
<!-- Other items -->
<input type = "hidden" name = "goHome" id = "goHome" value = "" />
</div>
</form>
<input type = "submit" name = "submitBtnF" id = "submitBtnF" class="shortText" style = "width: 120px;" value = "Submit + Home" onclick = "return getGoValue(true)"/>
<input type = "submit" name = "submitBtnR" id = "submitBtnT" class="shortText" style = "width: 120px;" value = "Submit + Next" onclick = "return getGoValue(false)"/>
Change your getGoValue() and checkNSub() functions like this :
function checkNSub() {
//form validation functions
//OK then return true
//Not then return false
var myForm = document.getElementById('addDataReal');
myForm.submit();
}
function getGoValue(goHome) {
if (goHome) {
document.getElementById("goHome").value = "true";
console.log(document.getElementById("goHome").value);
checkNSub();
} else {
document.getElementById("goHome").value = "false";
console.log(document.getElementById("goHome").value);
checkNSub();
}
return true;
}
Try it out.
P.S : A couple of console.logs so you can check out the value changing. Comment out checkNSub(); to see them in your console. Nevertheless keep in mind that you are posting a Form which means you are going to load a new page from the server , this new page will be agnostic regarding your "goHome" value. The "goHome" value exists only while you are on the same page. The moment your DOM is "recreated" you will lose it.
P.S.2 :
Your return true; inside the getGoValue(); is not needed in my
example. You can remove it.
the return in your onclick = "return getGoValue(true)" is also
not needed and you can remove it
P.S.3 :
This reply is focused on keeping most of your code intact. In reality now that you have your inputs outside the form there is no need for them to be of type="submit" you should change them to <button> with onClick events (or Listeners).
can any one tell me what is option for readonly for checkbox because I want to submit the value for the checkbox and at the same time want to achive the functionality of disable the attribute but using disable does not submit the value and I think readonly is not working in checkbox.
Please help me.
You can try something like this
<form action = "your url here" method = "POST">
NonEditableValue<input type = "checkbox"/ id = "mycheckbox" value = "ValueIwantChecked">
<input type = "submit" id = "somebutton" value = "Get CheckBox Value" />
</form>
​Javascript
$("#somebutton").click(function(e){
var ischecked = $('#mycheckbox').attr('checked')?true:false;
if(!ischecked){
e.preventDefault();
alert("Please select value");
}
else{
$("#mycheckbox").attr("disabled","true");
alert($("#mycheckbox").val());
}
});
This will disable the checkbox on submit and the alert in the "else" of javascript gives the value of the check box.Thus the value is preserved.
Hope this helps ..
WHen you want to disable the click Just return false:
<input type="checkbox" onclick="return false"/>
This will make sure that you can't change the value of the checkbox
try this one
<input name="chkbox1" type=checkbox readonly>check box 1</input>