I have a form that I need to do some validation on, my jquery seems to be working except when a user just enters the page and submits without making any entry into a text box. Here is my HTML:
...
<% while (rs.next()) { %>
<input type="text" name="name" />
<% } %>
<input type="text" id="fafsaNbrFam" name="fafsaNbrFam" value="<%=nbrFam%>" class="hidden" />
....
and my script:
$("#submit").click(function(e) {
var numEntries = 0;
var fafsaNbr = 0;
$("input[name^='name_']").each(function() {
if (this.value) {
numEntries++;
}
});
fafsaNbr = parseInt($("input[name='fafsaNbrFam']").val());
if (fafsaNbr > numEntries && !confirm("WARNING, numbers don't match.")) {
e.preventDefault();
}
});
So basically if their number of text boxes filled with names isn't >= the hidden input value then the kick back happens, and it works except when the user never enters anything into the text box. What event could I use instead of
$("input[name^='name_']").each(function() {
to accomplish this?
According to me it wont work because when textbox is empty then
$("input[name^='name_']").each(function()
parseInt($("input[name='fafsaNbrFam']").val());
.each() and val() return null. Due to this your control did not run ahead.
One thing you can do:
document.getElementById("fafsaNbrFam")==null
using this you can check the value as true or false. Because in case of empty textbox when you write the document.getElementById("fafsaNbrFam") or $("#fafsaNbrFam") it return value null.
And, null.val() or null.each() gives error.
Related
I'm trying to create a script that keeps our main button disabled until specific field requriments are met.
jQuery(document).ready(function() {//check if all are filled else disable submit
var inputFields = jQuery('#list-item-cc input, #field_28_50 input,#field_28_18 input');
inputFields.keyup(function() {
var empty = false;
inputFields.each(function() {
if (jQuery(this).val().length == 0) {
empty = true;
}
});
if (empty) {
jQuery('#gform_submit_button_28').attr('disabled', 'disabled');
} else {
jQuery('#gform_submit_button_28').removeAttr('disabled');
}
I'm having trouble thinking of a way to ensure my inputFields variable can be passed to my inputFields.each(function() in a way that would allow the loop.
We're not worried about all input fields. Just the specific inputs in our inputFields variable.
Is this an effective way to ensure a button is disabled if certain fields are not filled out and can I create the selector in the way that i did and use that in an each statement?
Looks like you are using gravity forms? In that case I would add a css class to each field that you want to validate. That way you don't have to go searching for ID's and change the code for multiple forms.
https://docs.gravityforms.com/css-ready-classes/
Here is a fiddle in which I pretend that I added "ensure-filled" to each item in the gravity forms builder
https://jsfiddle.net/dokLz4hm/3/
Also note that I added a .trim() to the value so that blank spaces aren't counted as input and made the submit button generic so it would work with any field in a form that contains the ensure-filled class
Html
<div>
<div id="arbitraty_id_1">
<input type="text" class="ensure-filled" />
</div>
<div id="arbitraty_id_2">
<input type="text" class="ensure-filled" />
</div>
<div id="arbitraty_id_3">
<input type="text" class="ensure-filled" />
</div>
<input type="submit" value="submit" disabled>
</div>
JS
$(document).ready(function() {
var inputFields = $('.ensure-filled');
inputFields.keyup(function() {
var empty = false;
inputFields.each(function() {
if ($(this).val().trim().length == 0) {
empty = true;
}
});
$('input[type="submit"]').attr('disabled', empty);
})
})
Edit: |SOLVED| user Jaromanda X's solution worked perfectly. Thank you
My goal is to have the user enter a bit of text into the textbox and submit it. I want to check and see if the textbox is empty and, if so, it should alert the user that a name needs to be entered. If it is not empty I want it to display the text they had entered.
The issue is this: Every time I hit submit it takes the value of the textbox - empty or not - and displays it without ever alerting the user of an empty text field. I feel like I'm missing something very basic. Thank you for your help!
HTML File
<body>
<div id="statusBar">
<h1 id="playerName"></h1>
<h2 id="playerHP"></h2>
</div>
<div id="gameWindow">
Player Name: <input id="inputName" type="text" name="Player Name">
<br>
<input type="button" value="submit" onclick="getStats()";>
</div>
<script src="script.js"></script>
</body>
JS File
function getStats(){
if(document.getElementById("inputName").len === " "){
alert('You must enter a name!');
} else {
var playerHP = 10;
var playerName = document.getElementById('inputName').value;
//Display player name on screen
document.getElementById('playerName').innerHTML = playerName;
//remove the value placed in the text box
document.getElementById('inputName').value = "";
//Display the player's HP
document.getElementById('playerHP').innerHTML = playerHP;
}
};
Change your if statement to:
if (document.getElementById("inputName").value.length === 0) {
Right now you're trying to get a property len of your <input> element, which doesn't exist. You should first be getting the value of the input, and checking if its length is zero. Hence, .value.length.
It should be:
if (document.getElementById("inputName").value === "") {
// do something
}
You're not using the right conditional.
Replace the
document.getElementById("inputName").len
with
document.getElementById("inputName").value.length === 0.
If you have a form, type some text into it, and press the Enter key, whenever revisiting that form you can double-click on the input box and see the past text submissions.
I have a site that when you press Enter OR click a button, it should take whatever is in the text box and use it for data processing.
This works totally fine when not surrounded by a form but when surrounded by a form an you press the Enter key, it does not act as an enter button push, I believe it's being overridden by the form.
My goal is to have the user be able to press the Enter key as well as click the button to submit the data, but to also remember the text values that were in the text box regardless of which way you submitted the data.
What I have:
<input type="text" id="username-field" class="form-control" placeholder="username">
<input class="btn btn-default" type="button" id="get-name" value="Get Name">
Javascript
$("#get-name").click(function() {
var name = $("#username-field").val();
// ... call other function with name ...
});
$("#get-name").keydown(function(e) {
if (e.which == 13) {
var name = $("#username-field").val();
// ... call other function with name ...
}
");
What I would like to use:
<form>
<input type="text" id="username-field" class="form-control" placeholder="username">
</form>
I tried doing e.preventDefault() when the Enter key is pressed, but this does not remember the text in the input field.
I also considered doing a small cache type thing but am unsure of how I'd go about this.
Any help would be much appreciated!
Thanks!
Doesn't use form at all. Just, why you added it, if you don't use it as intended?
You either mistyped provided code copy-paste, or have errors in yours script (the $("#get-name").val() mistake).
If you want to prevent form from submission, you should e.preventDefault()-it in submission handler, and return false from it:
$('#form-id').submit(function (e) {
e.preventDefault();
// do smth. else here
...
return false;
})
Saving/retriving data with localStorage for HTML5-supporting browsers:
$(function () {
$('form input[type=text]').doubleclick(function () {
var id = $(this).attr("id");
value = localStorage.getItem("form_xxx_" + id);
// do smth. with cached value, ie:
if (value != "")
$(this).val(value); // put in textfield
});
});
$('form').submit(function (e) {
$('form input[type=text]').each(function () {
var id = $(this).attr("id");
localStorage.setItem("form_xxx_" + id, $(this).val());
});
...
// all other work
});
Note: make sure you don't put some user's personal data in browser's local storage -_-
So I have a simple log in that requires a user to input values from a json file into two different text boxes ,when the user name and (in this case I have used ID as password) matches then an alert appears to say... "welcome"
After the .click function is carried out the users text still remains in the text box, how can I get both text boxes to appear blank after the .click function?
$(document).ready(function() {
//Hide alert when page loads
$("#loginalert").hide();
$("#invalid").hide();
$("#loginbtn").click(function(event){
$.getJSON('result.json', function(jd) {
var id = $('#userName').val();
var name = $('#userName2').val();
var valid = false;
for (var i=0; i<jd.user.length; i++) {
if ((jd.user[i].ID == id) && (jd.user[i].name == name)) {
valid=true;
$('#loginalert').html('<img src="' + jd.user[i].imgpath + '"><br><p> Welcome: ' + jd.user[i].name + '</p><button type="button" id="btnhide" class="btn btn-primary btn-md">Hide</button>');
//show the alert after loading the information
$("#loginalert").stop().fadeIn('slow').animate({ opacity: 1.0 }, 3000)
$('#invalid').hide();
$('#btnhide').on('click', function(e){
//console.log('here');
e.preventDefault();
$('#loginalert').hide();
});
}
}
if (!valid) {
$('#invalid').fadeIn('slow');
$('#loginalert').hide();
}
});
}); });
username 1 and #username 2 are the text boxes - is there any way to get user name 2 to display in stars ****** when the user enters the password - this question is not that necessary but if i could also get that working that would be good.
thanks guys hope someone can help :)
is there any way to get user name 2 to display in stars ****** when
the user enters the password
You can use an input box with text property set as password. But that password masking character will be . instead of *. Not exactly sure, whether it will be a different character in some browsers.
<input type="password" id="txtPassword" />
text box to appear blank after .click function
You can set the .val() property of the jQuery objects of two those two textboxes.
$('#userName, #username2').val('');
Use <input type="password"> to show typing as stars.
Clear inputs by setting their value to be empty: $('#userName').val('');
And perhaps consider breaking your code down into a couple smaller functions so it's easier to follow.
document.getElementById("#myTextbox").value="";
This should get your textbox and set the value of it to "", which is blank.
Edit: JSFiddle
Another Method:
You can also add the script directly inside the button without using/creating a function.
<input id="inputId" type="name" />
<button onclick="document.querySelector('#inputId').value='';"> Clear </button>
Using querySelector:
<input id="inputId" type="name" />
<button onclick="click()"> Clear </button>
<script>
function click() {
document.querySelector('#inputId').value="";
}
</script>
I'm trying to leverage some form validation to do something it really wasn't designed to do. I have a table in my form and each row has a checkbox. I want to ensure that at least one of a specific type of checkbox is selected, if not I want to show a validation error. I am doing something similar with a text box with logic that looks like this:
function ValidateName() {
var $nameTextbox = $("#Name");
var $originalName = $("#OriginalName");
var nameText = $nameTextbox.val().toLowerCase();
var originalNameText = $originalName.val().toLowerCase();
//check to see if original name and group name match
if (nameText != originalNameText) {
//This isn't the same name we started with
if (uniqueNames.indexOf(nameText) > -1) {
//name isn't unique, throw validation error
var currentForm = $nameTextbox.closest("form");
//trigger validation
var errorArray = {};
errorArray["Name"] = 'Name must be unique';
currentForm.validate().showErrors(errorArray);
}
}
}
I've written something similar for the table and it works as long as I point the errorArray's index to the id of an input. However, I want to display the error somewhere more generic like the validation summary at the top of the form. How do I set up the error array to show on the form or the validation summary instead of a specific input? Is that even possible?
One way you could do this is you set a hidden input that is false when none are check and true if 1 or more are checked. You then listen to all the checkboxes by giving them all a class. I have an example shown below
http://jsfiddle.net/95acw2m9/
Html
<input type="hidden" id="IsCheckValue" name="IsCheckedValue" value="false"/>
<input type="checkbox" class="someCheckbox"/>
<input type="checkbox" class="someCheckbox"/>
<input type="checkbox" class="someCheckbox"/>
Jquery
$(document).ready(function(){
$(".someCheckbox").change(function(){
if($(".someCheckbox:checked ").length > 0){
$("#IsCheckValue").val("True")
}else{
$("#IsCheckValue").val("False")
}
})
})
Then pass that bool value in your model. In your controller method you can check the value of the bool. If the bool is false set the model to false like this
ModelState.AddModelError("Checkbox", "Must select one checkbox");
You can use the #Html.ValidationSummary() to display the error in your view.