I have two fields where the user can only write in one or the other, we validate the client side using the javascript below. The problem that I have is that the textboxes by default have a clear 'x' that when used doesn't trigger the javascript leaving one of the fields disabled.
How can I call the javascript function when the user clicks the clear 'x' of the textbox in order to get both fields enabled?
<asp:TextBox ID="txtFIELD1Val" runat="server" onKeyup="javascript:clearFields();" TabIndex="1" CssClass="cssTextbox"></asp:TextBox>
<asp:TextBox ID="txtFIELD2Val" runat="server" onKeyup="javascript:clearFields();" TabIndex="2" CssClass="cssTextbox"></asp:TextBox>
function clearFields() {
var txtFIELD1 = document.getElementById('<%= txtFIELD1Val.ClientID %>');
var txtFIELD2 = document.getElementById('<%= txtFIELD2Val.ClientID %>');
//Enable/Disable FIELD1 and FIELD2 fields based on text.
if (txtFIELD1.value == "" && txtFIELD2.value == "") {
txtFIELD1.disabled = false;
txtFIELD2.disabled = false;
}
else if (txtFIELD1.value == "" || txtFIELD2.value != "") {
txtFIELD1.disabled = true;
txtFIELD2.disabled = false;
}
else if (txtFIELD1.value != "" || txtFIELD2.value == "") {
txtFIELD1.disabled = false;
txtFIELD2.disabled = true;
}
}
Remove IE10's "clear field" X button on certain inputs?
See the second answer, seems to be the best approach to getting rid of the 'X' and the problems it's causing.
I am using a asp:Repeater control while trying to develop a screen as shown below:
Submit form
When ToolId is entered on the TextChanged Event I am getting value for MaxToolLife stored as double. When an user enter values greater than the stored value for the field ToolLife I need to show Yes/No popup stating "The value entered is greater than existing value. Do you want to proceed?" on button submit or textchanged event.
Currently I am using the below code but I am not getting Javascript alert.
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Convert.ToDouble(txtToolLifeAchieved.Text) > maxToolLife)
{
Page.ClientScript.RegisterStartupScript(Page.GetType(), "Confirm", "javascript:Confirm();", true);
if (hdnconfirm.Value=="Yes")
{
row["Pcs Produced"] = Convert.ToDouble(txtToolLifeAchieved.Text);
}
else
{
txtToolLifeAchieved.Text = "1";
txtToolLifeAchieved.Focus();
return;
}
}
else
{
row["Pcs Produced"] = Convert.ToDouble(txtToolLifeAchieved.Text);
}
}
In place of Page.ClientScript I have also used "Page.ClientScript.RegisterClientScriptBlock" & /ScriptManager.RegisterStartupScript. Nothing is working as of now. I am unable to call the javascript function from code behind. Any immediate response would help a lot.
The confirm() is as shown below:
function Confirm()
{
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("The data already exists. Do you want to Overwrite data?"))
{
confirm_value.value = "Yes";
document.getElementById('<%= hdnconfirm.ClientID %>').value = "Yes";
}
else
{
confirm_value.value = "No";
document.getElementById('<%= hdnconfirm.ClientID %>').value = "No";
}
document.forms[0].appendChild(confirm_value);
}
So, I will stick to your original code, and this is how your server method should look like:
// This is just to illustrate the limit
private const double MaxToolLife = 100;
protected void btnSubmit_Click(object sender, EventArgs e)
{
// Check the limit first
if (Convert.ToDouble(txtToolLifeAchieved.Text) > MaxToolLife)
{
// If the hidden field is empty show the confirm
// By default the hidden field is empty, it means that user just
// pressed the submit button but not the confirmation dialog
if (string.IsNullOrWhiteSpace(hdnconfirm.Value))
{
ClientScript.RegisterStartupScript(this.GetType(), "Confirm", "Confirm();", true);
return;
}
// If the hidden field is not empty, this postback was made by the confirm
// So check for the value of the hidden field
if (hdnconfirm.Value == "Yes")
{
// Handle 'Yes'
}
else
{
// Handle 'No'
}
}
else
{
// The limit is not reached
}
}
I omitted your specific code above. This is how the form looks like:
<form id="form1" runat="server">
<!-- Hidden field for the confirm result -->
<asp:HiddenField ID="hdnconfirm" runat="server" />
<!-- Text box for user input -->
<asp:TextBox ID="txtToolLifeAchieved" runat="server"></asp:TextBox>
<!-- Submit button -->
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
</form>
Than right before the form tag in your page, place your javascript function, it must be place before the form tag, because calling ClientScript.RegisterStartupScript will append the script at the end of your form tag and that time your Confirm() method be defined. And this is your javascript method:
<script type="text/javascript">
function Confirm() {
if (confirm("The data already exists. Do you want to Overwrite data?")) {
document.getElementById('<%= hdnconfirm.ClientID %>').value = "Yes";
}
else {
document.getElementById('<%= hdnconfirm.ClientID %>').value = "No";
}
// Post the form back to server using the '__EVENTTARGET' hidden field
var form = document.getElementById("form1");
// Create hidden field
var input = document.createElement("input");
input.setAttribute("type", "hidden");
input.setAttribute("name", "__EVENTTARGET");
input.setAttribute("id", "__EVENTTARGET");
input.setAttribute("value", '<%= btnSubmit.ClientID %>');
// Append input to the form element
form.appendChild(input);
// Submit the form
form.submit();
}
</script>
There is no need to create another hidden field for the confirmation result. Instead just right after the confirm you need to create hidden field with name set to __EVENTTARGET, and the value of that hidden field must be the name of the submit button, and than just call submit method on the form. This will case postback to the server, with the hdnconfirm set to Yes or No while your btnSubmit_Click method will be executed.
I have created a form using bootstrap and am using javascript for form validation and then a php script to grab the post data and display it
the basic structure is the following and I have made this as minimal as I could to address this specific issue. The issue I am having is that the script to check for the form validation works perfectly in the <script> tags at the end of the body, but instead of preventing the page from being submitted as it should it still processes to the next page with the form's contents that are being made through the php post action when the form is indeed not filled out correctly.
Why is this? Should the form validation still not stop the page from moving on to the post data since the validation is returning false if the form has not been submitted correctly. All the form validation alerts pop up correctly and I;m getting no console errors after checking, or do I need to perform an additional check to only process the post data if the form is valid?
<html>
other tags.....
<body>
<form name = "OrderForm" action = "process_order.php" onsubmit = "orderbutton" method = "post">
a bunch of content, divs, checkboxes, etc
</form>
</body>
<script>
function CheckForm() {
var Name = document.getElementById("Name");
var fries = document.forms.OrderForm.FryRadio;
var fryyes = fries[0].checked
var fryno = fries[1].checked
var bool = true;
if ((Name.value == "" || Name.value == "Name") || (!(document.getElementById("SandwichRadio").checked || document.getElementById("WrapRadio").checked))) {
bool = false;
}
else if (!(fryyes || fryno)) {
bool = false;
}
if (!(bool)) {
alert("Please fill out all of the required fields.");
return false;
}
else {
alert("Your order is being submitted");
console.log("Submitted")
}
};
</script>
</html>
You should call function on submit , I dont know what are you doing with current onsubmit='...'
So use following, call function when you submit the form.
<form name = "OrderForm" action = "process_order.php" onsubmit = "return CheckForm()" method = "post">
a bunch of content, divs, checkboxes, etc
</form>
For demo : Check Fiddle
first of all what you can do is:
you do not need the !fryes in another if statement:
you can do it also in the first if:
if ((Name.value == "" || Name.value == "Name") || (!(document.getElementById("SandwichRadio").checked || document.getElementById("WrapRadio").checked)) || ( (!(fryyes || fryno))) {
bool = false;
}
also what you can do is if bool is false, disable your submit button if there is any?
you can also do an onchange on the texboxes, that way you can validate each text box or checkbox one by one. and have the bool true and false?
I did something like this on jquery long time ago, for validation, where I checked each texbox or dropdown against database and then validate, aswell..
The code is below
<script>
$(document).ready(function(){
var works=true;
//Coding for the captcha, to see if the user has typed the correct text
$('#mycaptcha').on('keyup',function(){
if($('#mycaptcha').val().length>=5){
$.post("user_test/captcha_check.php",
{
// userid: $("#userlogin").val(),
mocaptcha: $("#mycaptcha").val(),
},
function(data,status){
if(data==0){
document.getElementById("final_error").innerHTML="Captcha did not match";
works=false;
}
if(data==1){
works=true;
document.getElementById("final_error").innerHTML="";
}
});
}
});
//Works like a flag, if any mistake in the form it will turn to false
//Coding the submit button...
$('#submitbtn').on('click',function(){
var arrLang = [];
var arrPrf = [];
uid = $("#userid").val();
capc = $('#mycaptcha').val();
pwd = $("#pwd1").val();
fname = $("#fname").val();
lname = $("#lname").val();
email = $("#memail").val();
pass = $("#pwd2, #pwd1").val();
daysel = $('#dayselect').val();
monthsel = $('#monthselect').val();
yearsel = $('#yearselect').val();
agree_term = $('#agree_box').prop('checked');
//checks if the textboxes are empty it will change the flag to false;
if((!uid) || (!capc) ||(!fname) || (!lname) || (!email) || (!pass) || (!daysel) || (!monthsel) || (!yearsel) || (!agree_term)){
works=false;
}
if(!works){
document.getElementById('final_error').innerHTML ="<font size='1.3px' color='red'>Please fill the form, accept the agreement and re-submit your form</font>";
}
else{
works=true;
//A jquery function, that goes through the array of selects and then adds them to the array called arrLang
$('[id=lang]').each(function (i, item) {
var lang = $(item).val();
arrLang.push(lang);
});
//A jquery function, that goes through the array of select prof and then adds them to the array called arrprf
$('[id=prof]').each(function (i, item) {
var prof = $(item).val();
arrPrf.push(prof);
});
var data0 = {fname: fname, mlname : lname, userid : uid,password:pwd, emailid : email, mylanguage : arrLang, proficient : arrPrf, dob : yearsel+"-"+monthsel+"-"+daysel};
//var json = JSON2.stringify(data0 );
$.post("Register_action.php",
{
// userid: $("#userlogin").val(),
json: data0,
},
function(data,status){
if(data==1){
//alert(data);
window.location = 'Registered.php';
}
document.getElementById("userid_error").innerHTML=data;
});
}
});
//to open the agreement in a seperate page to read it..
$("#load_agreement").click(function () {
window.open("agreement.html", "PopupWindow", "width=600,height=600,scrollbars=yes,resizable=no");
});
//A code that loads, another page inside the agreement div
$( "#agreement" ).load( "agreement.html" );
//This part here will keep generating, duplicate of the language and profeciency box, incase someone needs it
$('#Add').click(function(){
//we select the box clone it and insert it after the box
$('#lang').clone().insertAfter("#lang").before('<br>');
$('#prof').clone().insertAfter("#prof").before('<br>');
});
//this part here generates number 1-31 and adds into month and days
i=0;
for(i=1; i<=31; i++){
$('#dayselect').append($('<option>', {value:i, text:i}));
if(i<=12){
$('#monthselect').append($('<option>', {value:i, text:i}));
}
}
//this code here generates years, will work for the last, 120 years
year=(new Date).getFullYear()-120;
i = (new Date).getFullYear()-16;
for(i; i>=year; i--){
$('#yearselect').append($('<option>', {value:i, text:i}));
}
//Regex Patterns
var pass = /^[a-z0-9\.\-\)\(\_)]+$/i;
var uname = /^[a-z0-9\.\-]+$/i;
var mname = /^[a-z ]+$/i;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
//When the Last Name texbox is changing this will be invoked
$("#fname").keydown(function(){
//comparing the above regex to the value in the texbox, if not from the box then send error
if(!mname.test($("#fname").val())){
//fill the textbox label with error
document.getElementById("fname_error").innerHTML="<font color='red' size='2px' family='verdana'>Invalid FirstName</font>";
$("#fname").css("border-color","rgba(255,0,0,.6)");
works=false;
}
else{
$("#fname").css("border-color","rgba(0,255,100,.6)");
document.getElementById("fname_error").innerHTML="";
works = true;
}
});//end of fname onchange
//When the Last Name texbox is changint this will be invoked
$("#lname").keydown(function(){
//comparing the above regex to the value in the texbox
if(!mname.test($("#lname").val())){
//fill the textbox label with error
document.getElementById("lname_error").innerHTML="<font color='red' size='2px' family='verdana'>Invalid LastName</font>";
$("#lname").css("border-color","rgba(255,0,0,.6");
works=false;
}
else{
$("#lname").css("border-color","rgba(0,255,100,.6)");
document.getElementById("lname_error").innerHTML="";
works = true;
}
});//end of lname on change
//When the userid textbox is chaning,this will be invoked
$("#userid").keydown(function(){
//comparing the above regex to the value in the texbox
if(!uname.test($("#userid").val())){
//fill the textbox label with error
document.getElementById("userid_error").innerHTML="<font color='red' size='2px' family='verdana'>Invalid UserId</font>";
$("#userid").css("border-color","rgba(255,0,0,.6");
works=false;
}
/*
else if($("#userid").val().length<4){
//fill the textbox label with error
document.getElementById("userid_error").innerHTML="<font color='red' size='2px' family='verdana'>Minimum user length is 4</font>";
$("#userid").css("border-color","rgba(255,0,0,.6");
//disable the submit button
//$('#submitbtn').attr('disabled','disabled');
works=false;
}
*/
else{
$("#userid").css("border-color","rgba(0,0,0,.3)");
$.post("user_test/user_email_test.php",
{
// userid: $("#userlogin").val(),
userid: $("#userid").val(),
},
function(data,status){
document.getElementById("userid_error").innerHTML=data;
});
works = true;
}
});//end of change
//When the userid textbox is chaning,this will be invoked
$("#memail").keydown(function(){
//comparing the above regex to the value in the texbox
if(!emailReg.test($("#memail").val())){
//fill the textbox label with error
document.getElementById("email_error").innerHTML="<font color='red' size='2px' family='verdana'>Invalid Email</font>";
$("#memail").css("border-color","rgba(255,0,0,.6");
works=false;
}
else{
works = true;
$.post("./user_test/user_email_test.php",{
useremail: $("#memail").val(),
},
function(data,status){
document.getElementById("email_error").innerHTML=data;
$("#memail").css("border-color","rgba(0,255,0,.3)");
works = true;
});
}
});//end of change
//When the userid textbox is chaning,this will be invoked
$("#pwd2").keyup(function(){
//checking length of the password
if($("#pwd2").val().length<10){
document.getElementById("pwd_error").innerHTML="<font color='red' size='2px' family='verdana'>Please enter a password minimum 10 characters</font>";
//$('#submitbtn').attr('disabled','disabled');
$("#pwd1, pwd2").css("border-color","rgba(0,255,100,.6)");
works=false;
}
//checking if the password matches
else if($("#pwd1").val()!=$("#pwd2").val()){
document.getElementById("pwd_error").innerHTML="<font color='red' size='2px' family='verdana'>Passwords do not match</font>";
//$('#submitbtn').attr('disabled','disabled');
works=false;
$("#pwd1, pwd2").css("border-color","rgba(0,255,100,.6)");
}
else{
$("#pwd1, #pwd2").css("border-color","rgba(0,0,0,.3)");
document.getElementById("pwd_error").innerHTML="";
//comparing the above regex to the value in the texbox and checking if the lenght is atleast 10
if(!pass.test($("#pwd2").val())){
//fill the textbox label with error
document.getElementById("pwd_error").innerHTML="<font color='red' size='1px' family='verdana'>Your password contains invalid character, Please use: a-z 0-9.( )_- only</font>";
$("#pwd1, #pwd2").css("border-color","rgba(255,0,0,.6");
works = false;
}
else{
$("#pwd1 , #pwd2").css("border-color","rgba(0,255,100,.6)");
works = true;
}
}
});//end of change
});//end of document ready
</script>
So i already have a textbox in which you can only enter numbers and they have to be within a certain range.The textbox defaults to 1,and i want to stop the user from being able to make it blank.Any ideas guys?Cheers
<SCRIPT language=Javascript>
window.addEventListener("load", function () {
document.getElementById("quantity").addEventListener("keyup", function (evt) {
var target = evt.target;
target.value = target.value.replace(/[^\d]/, "");
if (parseInt(target.value, 10) > <%=dvd5.getQuantityInStock()%>) {
target.value = target.value.slice(0, target.value.length - 1);
}
}, false);
});
<form action="RegServlet" method="post"><p>Enter quantity you would like to purchase :
<input name="quantity" id="quantity" size=15 type="text" value="1" />
You could use your onkeyup listener to check if the input's value is empty. Something along the lines of:
if(target.value == null || target.value === "")
target.value = 1;
}
You could add a function to validate the form when the text box loses focus. I ported the following code at http://forums.asp.net/t/1660697.aspx/1, but it hasn't been tested:
document.getELementById("quantity").onblur = function validate() {
if (document.getElementById("quantity").value == "") {
alert("Quantity can not be blank");
document.getElementById("quantity").focus();
return false;
}
return true;
}
save the text when keydown
check empty when keyup, if empty, restore the saved text, otherwise update the saved text.
And you could try the new type="number" to enforce only number input
See this jsfiddle
I'm gettig a bit lost with some javascript logic.
I have a form with 3 text fields.
They show a default value through a javascript (no placeholder).
When the form is focused, the value is cleared and when the form is blurred, the default value is restored if the field value hasn't been change.
I have to write some conditional logic to ensure that the field text color is changed from grey (default placeholder value) to black if the value is changed.
The 3 fields have a different default value. I tried to write a general script on Blur to check the value of the current field to test it against the default value.
$fields = $('#webform-component-group-1 .webform-component-watermarked');
var keys = [];
var values = [];
console.log($fields.length);
$fields.each(function(){
keys.push($(this).attr('id'));
values.push($(this).val());
$(this).blur(function(){
console.log($(this).val());
console.log($(this).val() !== values[keys.indexOf($(this).attr('id'))]);
});
});
but my test always return true as the placeholder value is not restored when I run the test on blur.
What would be the best way to handle this problem?
Cheers
Using jQuery, you could do it like this:
Assuming the following HTML
<div id='fields'>
<input value='start1' class='placeholder' />
<input value='start2' class='placeholder' />
</div>
JavaScript
$('#fields input').each(function(){
// Save initial placeholder values
$(this).data('placeholder', $(this).val());
}).on("focus", function(){
// Remove placeholder value and color on focus
if( $(this).val() === $(this).data('placeholder') ){
$(this).val('').removeClass('placeholder');
}
}).on("blur", function(){
// Restore placeholder on blur if input is empty
if( $(this).val().length === 0 ){
$(this).val($(this).data('placeholder')).addClass('placeholder');
}
});
CSS
input.placeholder{
color:#ccc;
}
input{
color:#000;
}
Fiddle: http://jsfiddle.net/uWPJC/
Try to play with this code , you will get what u looking for
var pass1 = document.getElementById('password');
var pass2 = document.getElementById('vpass');
var message = document.getElementById('confirmMessage');
var goodColor = "#66cc66";
var badColor = "#ff6666";
if(pass1.value == pass2.value){
pass2.style.backgroundColor = goodColor;
}
else{
pass2.style.backgroundColor = badColor;
}