I have the following code to put helper text in a search input box that is removed when you click in the box and returned if you click anywhere else without changing it:
$('#search-form input[type="text"]').each(function(){
var defaultVal = 'Category Search';
$(this).focus(function(){
if ($(this).val() == defaultVal){
$(this).removeClass('active').val('').css('color', '#000');;
}
})
.blur(function(){
if ($(this).val() == ''){
$(this).addClass('active').val(defaultVal).css('color', '#CCC');
}
})
.blur().addClass('active');
});
But if the user clicks submit without clicking in the input box, the site will search for the helper value (Category Search).
What I need to do is on submit check the value and if it's Category Search then do the following things:
Change helper text to Please enter a category
Don't submit the form.
I tried this but it stopped my default value (Category Search) from working all together:
$('#search-form input[type="submit"]').click(function() {
if ($(this).val() == "Category Search")
//do stuff here
});
jsBin demo
var defaultVal = 'Category Search';
var enterCat = 'Please enter a category';
$('#search-form input[type="text"]').each(function(){
$(this).focus(function(){
if ($(this).val() == defaultVal || $(this).val() == enterCat){
$(this).removeClass('active').val('').css('color', '#000');
}
})
.blur(function(){
if ($.trim($(this).val()) === ''){
$(this).addClass('active').val(defaultVal).css('color', '#CCC');
}
})
.blur().addClass('active');
});
$('#search-form').submit(function(e) {
if ( $(this).find('[type="text"]').val() === defaultVal){
e.preventDefault();
$(this).find('[type="text"]').prop('value', enterCat);
}
});
and use also $.trim() (whitespaces) before searching for blank inputs :)
HTML5 placeholder is what you should use for browsers that support it, there would be no code to write to remove it.
For browsers that do not support it, there are plenty of plugins that make it work.
And why do you not just ignore the default value on the server? Seems like a logical place to filter it out.
The reason why your code fails is this is the submit button, not the form fields!
$('#search-form input[type="submit"]').click(function() {
if ($(this).val() == "Category Search") <-- this is the submit button, not the input
//do stuff here
});
You need to change it to point to the inputs
$('#search-form').on("submit",function() {
$('#search-form input[type="text"]').each( function() {
//do comparison here, you could use defaultValue attribute
} );
});
I agree on using placeholder, but this is the answer to your question:
$('#search-form input[type="submit"]').click(function() {
if ($('#search-form input[type="text"]') == "Category Search")
$('#search-form input[type="text"]').val("Please enter a category");
return false;
});
I, personally, would create an error box near to the search field rather than change the text already in it - otherwise you're going to have problems with people submitting 'please enter a category'...
You are trying to get the .val() of the submit button
$('#search-form input[type="submit"]').click(function() {
if ($('#search-form input[type="text"]').val() == "Category Search")
//do stuff here
});
but you should probably hook it to submit event of the form itself, but that would depend on how your implementation actually works.
$('#search-form').submit(function() {
if ($('#search-form input[type="text"]').val() == "Category Search")
//do stuff here
});
If you can't use the placeholder (and you really should if you can), then you could simply set the field to disabled:
$('#search-form input[type="submit"]').click(function() {
if ($(this).val() == "Category Search") {
$(this).prop('disabled',true);
}
});
The disabled attribute essentially guarantees that the field is 'not successful', and thus won't be submitted to the server.
A successful control is "valid" for submission. Every successful control has its control name paired with its current value as part of the submitted form data set. A successful control must be defined within a FORM element and must have a control name.
However:
Controls that are disabled cannot be successful...
Citation: http://www.w3.org/TR/html401/interact/forms.html#h-17.13.2.
Much simpler: Most new browsers will allow this:
<input type="text" placeholder="your prompt here" />
But for older browsers you can do this:
$(function() {
if ($.browser.msie) {
$('#search-form input[type="text"]').each(function(){
$(this).val($(this).attr("placeholder"));
});
}
$("#search-form").on("submit",function() {
var cnt=0,empty++;
$("#search-form input[type='text']").each(function(){
var box = $(this),val = box.val();
if (val == box.attr("placeholder")){
box.val("");
}
else {
box.val($.trim(val));
}
if (box.val()=="") empty++;
cnt++;
});
if (empty==cnt) return false;
});
});
Related
I am trying to find out how can I disable the submit button until all form fields are filled. I have seen there are many solutions online in jQuery and JS.
But what I am looking for is, instead of checking all fields every time when there is a change in the field value, isn't there a way that checks the all the fields altogether at once at the end just like 'required' attribute?
For example, if you see the below solution provided here here.
$("input[type='text'], textarea").on("keyup", function(){
// checking for all fields on "keyup"
if (
$(this).val() != ""
&& $("textarea").val() != ""
&& $("input[name='category']").is(":checked") == true
) {
$("input[type='submit']").removeAttr("disabled");
} else {
$("input[type='submit']").attr("disabled", "disabled");
}
});
$("input[name='category']").on("change", function () {
if (
$(this).val() != ""
&& $("textarea").val() != ""
&& $("input[name='category']").is(":checked") == true
) {
$("input[type='submit']").removeAttr("disabled");
} else {
$("input[type='submit']").attr("disabled", "disabled");
}
});
We can see it's checking for all fields every time on keyup or on change is called. But I need to know if there is any other efficient way rather than checking all fields every time on keyup or on change is called?
Ive been looking but cant seem to find much clarification...
I am creating a form -
If a user is to select an option for contact "email",
the user must enter a text value for email input type.
Here is a fiddle- https://jsfiddle.net/4s3bLf65/
if ($("input[name='option']").val()=='email') &&($("input[name='email1']").val() == '')
{
alert('Enter email');
return false;
}
I cant seem to figure out the proper syntax for the js...
Any suggestions?
Try that way:
if ($("input[name='option']:checked").val()=='email' && $("input[name='email1']").val() == '')
{
alert('Enter email');
return false;
}
Add your code to a click handler or submit handler so it executes when the button is pressed.
Your if had too many perentheses
You were not getting the value of the :checked box.
$(document).ready(function() {
$('input[name="btn_submit"]').click(function() {
if ($("input[name='option']:checked").val() == 'email' && $("input[name='email1']").val() == '') {
alert('Enter email');
return false;
}
});
});
Fiddle: https://jsfiddle.net/ojqa46a0/
I have a textbox that looks like this
<%= Html.TextBoxFor(model => model.ContactAddress, new { autocomplete = "off", maxlength = "75" })%>
in my javascript i have this
$('.save_button_cont').click(function (e) {
var addr1 = $('#ContactAddress').val();
if(addr1.indexOf("box") > -1) {
alert("HEY NO P.O. BOXES ALLOWED ");
}
document.forms[0].submit();
});
i was hoping that this would pop up the alert before posting if the user had 'box' in the textbox. it doesnt work though.
I want to show an alert if the user enters the string 'box' in their address (the textbox).
EDIT: on the submit i am going to use a confirm box to verify that the user wants to continue. thanks for the help
Using
$("#textboxid").blur(function(){
if( $("#textboxid").val() == "box"){
alert("box typed!");
}
});
this will make your life easy!
Try this -
$('.save_button_cont').click(function (e) {
var addr1 = $('#ContactAddress').val();
if(addr1.indexOf("box") > -1) {
alert("blah");
}else {
alert('Bleh');
}
alert("TEST");
$('form').eq(0).submit();
});
You can do this:
$('.save_button_cont').click(function (e) {
var addr1 = $('#ContactAddress').val();
if (addr1.indexOf("box") > -1) alert("blah");
else alert('Bleh');
$('#formID').submit();
});
Instead of:
if(~addr1.indexOf("box")) {...} else {...}
Try
if(addr1 === "box") {...} else {...}
You could use regex to test the string for the occurrence of "box". This will allow you to do a case-insensitive search:
$('input[type="submit"]').click(function(e) {
e.preventDefault();
var input = $('#test').val();
if (/box/i.test(input)) {
alert("bad");
} else {
alert("good");
$("form").submit();
}
});
You should also put the "submit" function in your "else" statement so the form only submits on validation success.
NOTE: this could cause unwanted issues if the user happens to live on "box street".
I am using the below code to show hide the default input value on focus. However, I am going to be using a few forms on one page and dont really want to have create this js for each input field, pretty time consuming and probably a bit too much js.
Html
<input type="text" class="sb" value="Search CT..."/>
Javascript
//search box
$("input.sb").focus(function(){
if ( $(this).val() == "Search CT...")
$(this).val('');
});
$("input.sb").blur(function(){
if ( $(this).val() == "")
$(this).val('Search CT...');
});
I was wondering if there was a way to create some generic JS to show/hide the default value, regardless of its content which would work on all form inputs??
Hope this makes sense, thanks very much.
This code will look through all your text input elements and textarea elements on page load. It will store their original values using $.data. It will then do the emptying and refilling as appropriate.
$(document).ready(function(){
$('form input:text, form textarea').each(function(){
$.data(this, 'default', this.value);
}).focus(function(){
if ($.data(this, 'default') == this.value) {
this.value = '';
}
}).blur(function(){
if (this.value == '') {
this.value = $.data(this, 'default');
}
});
});
Try below code -
$(document).ready(function(){
var value = '';
$("input.sb").focus(function(){
value = $(this).val();
if (value != ""){
$(this).val('');
}
});
$("input.sb").blur(function(){
if ( $(this).val() == ""){
$(this).val(value);
}
});
});
Looks like you're using jQuery. Have you tried using a plugin?
Here's one that will do what you need:
http://plugins.jquery.com/content/default-text-inputtext-fields-required-rule-modification
You could create a map, more or less like this:
Javascript
function setEvents( id, txt ){
$("#" + id)
.focus(function(){
if ( $(this).val() == txt) $(this).val('');
})
.blur(function(){
if ( $(this).val() == "") $(this).val(txt);
});
}
var map = {
input1: "your text",
input2: "other text"
};
for(var i in map){
setEvents( i, map[i] );
}
Where the keys of the map object represent input ID's and the values represent the default value
$("input").focus(function(){
$(this).val('');
});
or give a common class for each input field
I doing a field validation using jquery to check if it is empty. If it is I want to display a message and then refocus on the field so the user can enter some data. Code:
$('#fieldId').blur(function() {
var fieldValue = $(this).val();
if(fieldValue == null || fieldValue.length == 0) {
$(this).addClass('error');
// show error message
$('#errorDivId')
.text('You must enter a value in this field')
.show();
$(this).focus();
}
else {
if ($(this).is('.error')) {
$(this.removeClass('error');
$('#errorDivId').hide()
}
}
});
It sort of works but it moves the cursor to the next field and not the one I refocused on.
You can try this:
$('#fieldId').blur(function(evt) {
var fieldValue = $(this).val();
if(fieldValue == null || fieldValue.length == 0) {
$(this).addClass('error');
// show error message
$('#errorDivId')
.text('You must enter a value in this field')
.show();
this.focus();
evt.preventDefault();
}
else {
if ($(this).is('.error')) {
$(this.removeClass('error');
$('#errorDivId').hide()
}
}
});
However that may not completely solve the problem, as some browsers might be confused. As an alternative, wrap your "focus" call up as a timeout and run it after the current event finishes:
var self = this;
setTimeout(function() { self.focus(); }, 1);
It's kind-of a hack but it should also work.
edit — #Gus is right about which "focus()" to call
The blur event is triggered during a focus change (as the control you are validating loses focus). This could cause weird behaviour if you try to alter the focus while it is already changing. Instead of blur, try attaching the validation to the change event.
Also, there's no need to call the jQuery version of focus: $(this).focus(), you can just call this.focus().
$('#fieldId').change(function() {
var fieldValue = $(this).val();
if(fieldValue == null || fieldValue.length == 0) {
$(this).addClass('error');
// show error message
$('#errorDivId').text('You must enter a value in this field').show();
this.focus();
} else {
if ($(this).is('.error')) {
$(this).removeClass('error');
$('#errorDivId').hide()
}
}
});