I've the below ajax form. In the form I've got 2 textbox. There is a radio button to choose between Unlock and reset the password. All I want to do here is if I select unlock password label and textbox should disappear. I could do this with below javascript function only if the label and textbox were pure html. If I do that then Ajax doesnot pick up the value of password. Your help is much appreciated.
<input name="rblTooType" value="Unlock" type="radio" checked="checked" onclick="rblToolType_OnChange(true)" />Unlock
<input name="rblTooType" value="reset" type="radio" onclick="rblToolType_OnChange(false)" />reset Password
#using(Ajax.BeginForm("Search","User",new AjaxOptions {
UpdateTargetId = "divResults"
})){
#Html.Label("UserName")
#Html.TextBox("term")
#Html.Label("Password")
#Html.TextBox("Password")
<input id="btnSubmit" type="submit" value="Unlock"/>
}
<script type="text/javascript">
function rblToolType_OnChange(isUnlock) {
if (isUnlock) {
Password.style.display = "none";
btnSubmit.value = "Unlock";
}
else {
Password.style.display = "";
btnSubmit.value = "reset Password";
}
}
</script>
You seem to be depending on an old quirk of IE where element names and ids were added as global variables. It is bad practice to rely on that because other browsers don't support it (it was a very bad idea from the start). Reference your form elements correctly and it should work. e.g.
function rblToolType_OnChange(isUnlock) {
var form = document.forms['<form name>']
if (isUnlock) {
form.Password.style.display = "none";
form.btnSubmit.value = "Unlock";
}
else {
form.Password.style.display = "";
form.btnSubmit.value = "reset Password";
}
}
Related
I submited a form using javascript (must check pre-condition first), and I noticed that I'm not notified about unfilled required properties:
function offerContract() // the function called when deployContractBtn is clicked
{
document.getElementById("CreateContractDialogMessage").innerHTML = "";
ErrorMsg = checkErrors();
if (ErrorMsg != "")
{
$('#CreateContractDialogTitle').text("Error"); //show error headline
document.getElementById("CreateContractDialogMessage").innerHTML = ErrorMsg;
document.getElementById("closeButton").style.display = "block";
$('#dialogOfferContract').modal('show');
return;
}
$("#deployContractBtn").submit() //type = button and not submit
}
#using (Html.BeginForm("DeployContract", "CreateContract", FormMethod.Post, new { #id = "DeployContractForm" }))
{
.....The rest of the form....
<input id="deployContractBtn" onclick="offerContract()" type="button" class="btn btn-success" value="Sign&Deploy Contract" disabled />
}
How to notify about the unfilled requierd properties using javascript as the classic submit does? Is it possible to mark them, so the user will know where he needs to insert values?
If you want to leverage default browser UI, you can just mark the field as required. By default, the form will now allow a user to submit it until the requirements are met.
<form id="myForm">
<input placeholder="this field is required" required />
<button type="submit">Submit</button>
</form>
However, If you want a little more customization you can use JavaScript to do what you want.
const submitBtn = document.getElementById('submit');
submitBtn.addEventListener('click', (e) => {
const form = document.getElementById('myForm');
if (form.checkValidity()) {
// TODO: Submit form code here
console.log('Form submitted');
return;
} else {
const nameField = document.getElementById('nameField');
if (!nameField.checkValidity()) {
alert('The Name Field is a required field. Please provude a valid value');
}
}
});
<form id="myForm">
<input placeholder="this field is required" id="nameField" required />
</form>
<button id="submit">Submit</button>
I have a simple form inside a Pop up window. In my form I have only one checkbox with a label for the checkbox. What I have done is when the user clicks on the label or checkbox, the submit button to appear and the user will be able to submit the form. Moreover, I would like when the user press the submit button to collect the information in my database and then to close the pop up window and continue on the website normally without leaving. I am not sure how to achieve that but this is what I have done until now. Please I need some help to achieve this.
1) I want to submit the form successfully and collect the information to my database.
2) I want to close the PopUp Window.
3) I do not want to leave the page.
Thanks.
HTML:
<div id="popUp">
<form id="myform" method="post" action="somepage.php" onsubmit="return closeWindow">
<input type="checkbox" id="checkbox" name="checkbox"><label for="checkbox">Click to show Submit</label><br>
<input type="submit" id="submit-button" value="Submit" style="display:none">
</form>
</div>
CSS:
#popUp {
height:400px;
border:1px solid #000;
background:#e2e2e2;
}
JS:
var checkBox = document.getElementById("checkbox");
var submitButton = document.getElementById("submit-button");
var PopUpWindow = document.getElementById("popUp");
function checboxFunc() {
if (checkBox.checked) {
submitButton.style.display = "block";
} else {
submitButton.style.display = "none";
}
}
checkBox.addEventListener("click", checboxFunc);
function closeWindow() {
PopUpWindow.style.display = "none";
return false;
}
submitButton.addEventListener("click", closeWindow);
Although you could use AJAX, a simpler approach would be to put the form in another HTML file and load it into an iframe and set the form's target="name_of_iframe".
You will also have to get rid of the onsubmit attribute and instead add an event listener. Like so.
yourpage.html
<iframe id="popUp" name="popup" src="path/to/form.html"></iframe>
form.html
<form id="myform" method="post" action="somepage.php" target="popup">
<input type="checkbox" id="checkbox" name="checkbox"><label for="checkbox">Click to show Submit</label><br>
<input type="submit" id="submit-button" value="Submit" style="display:none">
</form>
yourpage.js
var checkBox = document.getElementById("checkbox");
var submitButton = document.getElementById("submit-button");
var PopUpWindow = document.getElementById("popUp");
var form = document.getElementById("myform");
function checboxFunc() {
if (checkBox.checked) {
submitButton.style.display = "block";
} else {
submitButton.style.display = "none";
}
}
checkBox.addEventListener("click", checboxFunc);
function closeWindow() {
PopUpWindow.style.display = "none";
return false;
}
form.addEventListener("submit", closeWindow);
When this is submitted, the somepage.php will load, but only inside the popup, wich will be hidden anyway. So you will have the desired effect.
Ajax was invented to solve this. Jquery wraps it nicely like:
checkout $.post
Two suggestions, if you are doing this type of request, dont complicate matters and use the FORM tag, just use the inputs.
Secondly send JSON instead of form data, can be messy trying to get in the correct format.
So your client side would look something like this:
var req_obj = {
"id":"ENTER_DATA",
"params":{
"param_name1":"param_val1",
"param_name2":"param_val2"
}
};
$.post(
APP.ActionUrl,
JSON.stringify(req_obj),
function(data){ //this is the callback,do your confirmation msg },
"json");
SERVER:
$req_obj = json_decode(get_post_data());
$param1 = $req_obj->params->param_name1;
function get_post_data(){
$buf = '';
if(($h_post = fopen('php://input','r'))){
while(!feof($h_post))
$buf .= fread($h_post,1024);
fclose($h_post);
return $buf;
}
else
return false;
}
I have a form in html which I want to run verification in Javascript first before POST ing to PHP. However the link up to the PHP section does not seem to be working despite the fact that I have assigned names to each input tag and specified an action attribute in the form tag.
Here is the HTML code for the form:
<form id="signupform" action="signupform.php" method="post">
<input type="text" name="Email" placeholder="Email Address" class="signupinput" id="email" />
<br />
<input type="password" name="Password" placeholder="Password" class="signupinput" id="passwordone" />
<br />
<input type="password" placeholder="Repeat Password" class="signupinput" id="passwordtwo" />
<br />
<input type="button" value="Sign Up" class="signupinput" onClick="verifypass()" id="submit" />
</form>
The button calls the javascript function which I use to verify the values of my form before sending to php:
function verifypass() {
var form = document.getElementById("signupform");
var email = document.getElementById("email").value;
var password1 = document.getElementById("passwordone").value;
var password2 = document.getElementById("passwordtwo").value;
var emailcode = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (emailcode.test(email)) {
if (password1.length > 6) {
if (password1 == password2) {
form.submit(); //this statement does not execute
} else {
$("#passwordone").notify("Passwords do not match!", {
position: "right"
})
}
} else {
$("#passwordone").notify("Password is too short!", {
position: "right"
})
}
} else {
$("#email").notify("The email address you have entered is invalid.", {
position: "right"
})
}
}
For some reason, some JavaScript implementations mix up HTML element IDs and code. If you use a different ID for your submit button it will work (id="somethingelse" instead of id="submit"):
<input type="button" value="Sign Up" class="signupinput" onClick="verifypass()" id="somethingelse" />
(I think id="submit" has the effect that the submit method is overwritten on the form node, using the button node. I never figured out why, perhaps to allow shortcuts like form.buttonid.value etc. I just avoid using possible method names as IDs.)
I'm not sure why that's not working, but you get around having to call form.submit(); if you use a <input type="submit"/> instead of <input type="button"/> and then use the onsubmit event instead of onclick. That way, IIRC, all you have to do is return true or false.
I think it would be better if you do it real time, for send error when the user leave each input. For example, there is an input, where you set the email address. When the onfocusout event occured in Javascript you can add an eventlistener which is call a checker function to the email input.
There is a quick example for handling form inputs. (Code below)
It is not protect you against the serious attacks, because in a perfect system you have to check on the both side.
Description for the Javascript example:
There is two input email, and password and there is a hidden button which is shown if everything is correct.
The email check and the password check functions are checking the input field values and if it isn't 3 mark length then show error for user.
The showIt funciton get a boolean if it is true it show the button to submit.
The last function is iterate through the fields object where we store the input fields status, and if there is a false it return false else its true. This is the boolean what the showIt function get.
Hope it is understandable.
<style>
#send {
display: none;
}
</style>
<form>
<input type="text" id="email"/>
<input type="password" id="password"/>
<button id="send" type="submit">Send</button>
</form>
<div id="error"></div>
<script>
var fields = {
email: false,
password: false
};
var email = document.getElementById("email");
email.addEventListener("focusout", emailCheck, false);
var password = document.getElementById("password");
password.addEventListener("focusout", passwordCheck, false);
function emailCheck(){
if(email.value.length < 3) {
document.getElementById("error").innerHTML = "Bad Email";
fields.email = false;
} else {
fields.email = true;
document.getElementById("error").innerHTML = "";
}
show = checkFields();
console.log("asdasd"+show);
showIt(show);
}
function passwordCheck(){
if(password.value.length < 3) {
document.getElementById("error").innerHTML = "Bad Password";
fields.password = false;
} else {
fields.password = true;
document.getElementById("error").innerHTML = "";
}
show = checkFields();
console.log(show);
showIt(show);
}
function showIt(show) {
if (show) {
document.getElementById("send").style.display = "block";
} else {
document.getElementById("send").style.display = "none";
}
}
function checkFields(){
isFalse = Object.keys(fields).map(function(objectKey, index) {
if (fields[objectKey] === false) {
return false;
}
});
console.log(isFalse);
if (isFalse.indexOf(false) >= 0) {
return false;
}
return true;
}
</script>
I wants to check, if entered field's value is valid or not using onchange before submitting the page. I have written like below.It validates well.But how to activate 'NEXT' button when there is no error on input entries.
<div><input type="text" name="your_name" id="your_name" onchange = "validate_Name(this,1,4)" />
<span id="your_name-error" class="signup-error">*</span>
</div>
<div><input type="text" name="your_addr" id="your_addr" onchange = "validate_Name(this,1,4)" />
<span id="your_addr-error" class="signup-error">*</span>
</div>
<input class="btnAction" type="button" name="next" id="next" value="Next" style="display:none;">
<script type="text/javascript" src="../inc/validate_js.js"></script>
<script>
$(document).ready(function() {
$("#next").click(function() {
var output = validate(); //return true if no error
if (output) {
var current = $(".active"); //activating NEXT button
} else {
alert("Please correct the fields.");
}
});
}
function validate() {
//What should write here?I want to analyse the validate_js.js value here.
}
</script>
Inside validate_js.js
function validate_Name(inputVal, minLeng, maxLeng) {
if (inputVal.value.length > maxLeng) {
inputVal.style.background = "red";
inputVal.nextElementSibling.innerHTML = "<br>Max Characters:" + maxLeng;
} else if (!(tBox.value.match(letters))) {
inputVal.style.background = "red";
inputVal.nextElementSibling.innerHTML = "<br>Use only a-zA-Z0-9_ ";
} else {
inputVal.style.background = "white";
inputVal.nextElementSibling.innerHTML = "";
}
}
If by "activating" you want to make it visible, you can call $('#next').show().
However if you want to simulate a click on it, with jQuery you can simply call $('#next').click() or $('#next').trigger('click') as described here. Also, you might want to put everything in a form and programmatically submit the form when the input passes validation.
You could possibly trigger the change event for each field so it validates each one again.
eg.
function validate() {
$("#your_name").trigger('change');
$("#your_addr").trigger('change');
}
I've cobbled together these javascript functions to hide the delivery address fields on my shopping cart address form if goods are going to billing address. The functions toggle visibility of html wrapped by ..
function getItem(id) {
var itm = false;
if(document.getElementById)
itm = document.getElementById(id);
else if(document.all)
itm = document.all[id];
else if(document.layers)
itm = document.layers[id];
return itm;
}
function showHideItem(id) {
itm = getItem(id);
if(!itm)
return false;
if(itm.style.display == 'none')
itm.style.display = '';
else
itm.style.display = 'none';
return false;
}
It works fine if were loading a new address form, the problem I have is if they submit the form with checkbox ticked, and validation fails, the form reloads with the checkbox ticked but unfortunately the fields are visible so now the removing the checkbox hides the fields!!
<tr><td class="white"><strong>Delivery Address</strong></td>
<td>Tick <input Type="checkbox" id="deliver_same" value="yes" onClick="showHideItem('delAddress')" />
If delivery address is billing address</td></tr>
<tbody id="delAddress">
<tr><td>Address line 1</td><td><input class="text" name="saddr1" value="" /></td></tr>
...
<tr><td>Post /Zip Code</td><td><input class="text" name="spostalcode" value="" /></td></tr>
</tbody>
I guess what I need is an onload event which hides the fields if checkbox is ticked when the form loads. Having just written that, I might have a go but not confident. Please, no mention of jquery, its not an option at this point of project.
function checkDeliverSame() {
var deliverSame = getItem('deliver_same');
var deliveryAddress = getItem('delAddress');
if (deliverSame.checked) {
deliveryAddress.style.display = 'none';
} else {
deliveryAddress.style.display = 'block';
}
}
checkDeliverSame(); /* This runs the function on page load */
Put that function, along with your getItem function, right above the </body> tag, and call it in the checkbox input onclick. You will also need to change the id#delAddress element from a tbody to a div so that the getItem function will work on it.
Here's a fiddle: http://jsfiddle.net/JuNhN/1/
I modified Josh's function to make it more generic, prefer document.getElementById() too as it fits in better with itm.style.display. I don't entirely trust checkDeliverSame(); going for a direct call in the html shortly after the closing tag.
function checkHiddenRows(id) {
deliverSame = getItem('deliver_same');
itm = document.getElementById(id);
if (deliverSame.checked == true) {
itm.style.display = 'none';
} // else { alert('Checkbox not checked') } // Verify the checkbox state
}
<script>checkHiddenRows('deliveryAddress');</script>
The form is now working as intended.