I am using MVC, not that this makes a difference, but I have a text box for searching.
<% using (Html.BeginForm("Index", "Search", FormMethod.Post)) { %>
<%= Html.AntiForgeryToken() %>
<div id="search_box">
<span id="search-title">Search Site</span>
<div>
<%= Html.TextBox("searchText", "type here, then press enter", new { #class = "search_input" }) %>
</div>
</div>
<% } %>
I used to have the onblur and onfocus events set on this text box to do some text swapping when the user clicked into it or out of it without typing anything. But, I moved them into a JS file because eventually, we want to add other functionality through JS, such as autocomplete, etc.
The problem with my JS is that it submits no matter what.
var searchHandler = function() {
var searchBox = "searchText";
var defaultText = "type here, then press enter";
var attachEvents = function() {
$("#" + searchBox).focus(function() {
if (this.value == defaultText) {
this.value = '';
}
}).blur(function() {
if (this.value == '') {
this.value = defaultText;
}
}).keyup(function(event) {
var searchTerms = $("#" + searchBox).val();
if (event.keyCode == 13 && searchTerms == '') {
return false;
}
else {
return true;
}
});
};
return {
init: function() {
$("#" + searchBox).val(defaultText)
attachEvents();
}
}
} ();
$().ready(function() {
searchHandler.init();
});
What I really need is to just make it so that enter does not submit the form if the textbox is empty. Any ideas?
If you use jQuery you can simply return a false if the validation rules are not met.
$(document).ready( function(){
$('form').submit(function(){
if( $('#searchText').val() == '')
return false;
else
return true; //just to be explicit, not really necessary.
});
});
Or something close to that.
Related
I have the following javascript to prevent the user from resubmitting the same search criteria without changing the text (SearchString) or the combo box (SearchType). The EnableSubmit works but has a problem that when the user adds and then removes a space, EnableSubmit falls over.
I try to keep the value of the last criteria in LastChange variable. Then when they submit it again, the alert box pops up. After the alert is closed, the code then looks like it is submitting and then they can then reclick submit with the same previous criteria. The question is, how can I after the alert box close then keep LastChange with the same value.
<script type="text/javascript">
var LastChange;
$("#SearchString").change(function () { EnableSubmit();});
$("#SearchString").keyup(function () { EnableSubmit(); });
$("#SearchType").change(function () { EnableSubmit(); })
function EnableSubmit () { $("#SubmitButton").removeAttr("disabled"); $("#SubmitButton").attr("value", "Search"); }
$(function () {
$("#StarForm").submit(function (e) {
$("#SubmitButton").attr("disabled", true);
$("#SubmitButton").attr("value", "Submit disabled until you change search criteria.");
if (LastChange == ($("#SearchString").val())) {
alert('Please change the search criteria before resubmitting.');
LastChange = ($("#SearchString").val());
}
else {
LastChange = ($("#SearchString").val());
var FormData = '{ "SearchString": "' + $('#SearchString').val() + '",' +
'"SearchType" : "' + $('#SearchType').val() + '"' +
'}';
e.preventDefault();
}
});
});
</script>
Perhaps put the enable/disable logic in your change handler and only set the last search criteria in your submit handler.
Maybe something like this?
$(function () {
var lastSearchText;
var lastSearchType;
$("#SearchString").change(function () { onSearchChanged();});
$("#SearchString").keyup(function () { onSearchChanged(); });
$("#SearchType").change(function () { onSearchChanged(); })
function onSearchChanged () {
var searchText = $("#SearchString").val().trim();
var searchType = $('#SearchType').val();
if (searchText !== lastSearchText || searchType !== lastSearchType) {
$("#SubmitButton").removeAttr("disabled");
$("#SubmitButton").attr("value", "Search");
}
else {
$("#SubmitButton").attr("disabled", true);
$("#SubmitButton").attr("value", "Submit disabled until you change search criteria.");
}
}
$("#StarForm").submit(function (e) {
lastSearchText = $("#SearchString").val().trim();
lastSearchType = $('#SearchType').val();
onSearchChanged();
});
});
When you're adding your listeners here:
$("#SearchString").keyup(function () { EnableSubmit();});
You first need to check if the text is different before you call EnableSubmit(). What you are currently doing is calling the function whenever a key is pressed. Adding an if statement before EnableSubmit() should fix your issue
Alternative solution:
Keep button disabled if the current search value is equal to the last submitted search value. I changed your EnableSubmit function to an EnableDisableSubmit and have added a variable currentValue to get the current value of the search input.
Here's the code:
var LastChange;
var currentValue;
$("#SearchString").change(function(e) {
EnableDisableSubmit(currentValue);
});
$("#SearchString").keyup(function(e) {
currentValue = $(this).val();
EnableDisableSubmit(currentValue);
});
$("#SearchType").change(function(e) {
EnableDisableSubmit(currentValue);
})
function EnableDisableSubmit(txt) {
if (txt !== LastChange) {
$("#SubmitButton").removeAttr("disabled");
$("#SubmitButton").attr("value", "Search");
} else {
$("#SubmitButton").attr("disabled", true);
$("#SubmitButton").attr("value", "Submit disabled until you change search criteria.");
}
}
$(function() {
$("#SubmitButton").click(function(e) {
$("#SubmitButton").attr("disabled", true);
$("#SubmitButton").attr("value", "Submit disabled until you change search criteria.");
LastChange = ($("#SearchString").val());
var FormData = '{ "SearchString": "' + $('#SearchString').val() + '",' +
'"SearchType" : "' + $('#SearchType').val() + '"' +
'}';
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id="SearchString" />
<button id="SubmitButton">Submit</button>
I am having trouble submitting the below form.
For background, I'm trying to "submit" a form for a delivery, and I need to know a) their pickup address, b) their dropoff address, and c) their description. I created <p class="error"> fields if those <input>s are empty (as in "Please enter a description").
If I remove the 'return false;' the form submits no matter what, but if I keep the 'return false;' the jQuery works (i.e. - error message appears) but now the form NEVER submits. Thoughts?
Here's my main.js
var main = function() {
$('form').submit(function() {
var pickup = $('#pickup').val();
if(pickup === "") {
$('.pickup-error').text("Please choose a pickup.");
}
var dropoff = $('#dropoff').val();
if(dropoff === "") {
$('.dropoff-error').text("Please choose a dropoff.");
}
var description = $('#description').val();
if(description === "") {
$('.description-error').text("Please tell us a little about what we're moving.");
}
return false;
});
};
$(document).ready(main);
var main = function () {
$('form').submit(function () {
var pickup = $('#pickup').val();
if (pickup === "") {
$('.pickup-error').text("Please choose a pickup.");
}
var dropoff = $('#dropoff').val();
if (dropoff === "") {
$('.dropoff-error').text("Please choose a dropoff.");
}
var description = $('#description').val();
if (description === "") {
$('.description-error').text("Please tell us a little about what we're moving.");
}
// did not pass validation
if (pickup != "" || dropoff != "" || description != "") {
return false;
}
// passed validation, submit
return true;
});
};
$(document).ready(main);
I have the following in my HTML thing, The input value will be populated by the user selection and store the values in the format of array( 45[45, 6, 33], 67[67,2,5] and so on.. ). Basically the value would be like the following:
<input id="question_string" type="hidden" value="{}">
<input class="submit_updates" name="commit" type="submit" value="Process">
Now i need to disable the submit button or alert some messages like 'Select all values' if the input has no arrays in the {}.
Updated:
var question_hash_element = document.getElementById('question_string');
var question_hash = JSON.parse(question_hash_element.value);
var myArray = new Array();
myArray[0] = window.batch_question_id;
myArray[1] = window.answer_id || window.answer_text || window.batch_answer_checkbox
myArray[2] = window.build_id
This bit of above code store the values into the {}. I just want to disable and let the user to select all the fields to process the form. If the values are {}, the button should disabled. and any of the values inside and it should be enabled.
I have tried like the following:
$('.submit_updates').click(function () {
if ($('#question_string') == {}) {
return false;
alert("Select all the Values");
} else {
return true;
}
});
It's not working..
Any help would be appreciated! Thanks
$('.submit_updates').on('click', function (e) {
e.preventDefault();
if ( $.trim($('#question_string').val())=='{}' ) {
alert('no question !');
}else{
this.form.submit();
}
});
You are returning false before alerting the message.
Try this:
$('.submit_updates').on("click", function () {
if ($('#question_string').val() == "{}") { //Adjusted condition
//Alert message
alert("Select all the Values");
//Disable the submit button
$(".submit_updates").prop("disabled", true);
return false;
} else {
return true; //Not really needed
}
});
It is nicer to use on and prop instead of click and attr, as #adeneo suggests.
Try this
$(function(){
$('.submit_updates').on('click', function () {
if ($('#question_string').val() == "{}") {
$(this).prop('disabled', 'disabled');
alert("Select all the Values");
} else {
}
});
});
DEMO
i used to use jquery validation plugin but because of lack of this plugin with wysiwyg plugins i wrote a simple script to validate my form
i tried to do it like this
function validateArticle(formData, jqForm, options) {
$('#errors').empty();
if ($('#editor').val() == 0) {
$('#errors').show();
$('#errors').append('<li>please enter your article body</li>');
return false;
}
if ($('#ArticleTitle').val() == 0) {
$('#errors').show();
$('#errors').append('<li>please enter your article title</li>');
return false;
}
$('#errors').hide();
return true ;
}
i found to 1 problem when it validate the form it's validating it field by field so the errors messages doesn't appear at once
i tried to do something like
var errors = [];
function validateArticle(formData, jqForm, options) {
$('#errors').empty();
if ($('#editor').val() == 0) {
errors.push('<li>please enter your article body</li>');
var invalid = 1 ;
return false;
}
if ($('#ArticleTitle').val() == 0) {
errors.push('<li>please enter your article title</li>');
var invalid = 1 ;
return false;
}
if(invalid == 1){
$.each(errors , function(i, val) {
$('#errors').append(errors [i]);
});
}
$('#errors').hide();
return true ;
}
i tried to push errors as array elements and loop through them in case of invalid is true
bu this one doesn't work at it all ?
is there any way to make it work ?
if ($('#editor').val() == 0) // This is checking if value is 0
This does not make sense..
Try
if ($('#editor').val() == '') //Instead check for empty string
EDIT
Also you seem to be hiding the error's div in the end.
$('#errors').hide();
Try this code Instead
$('#validate').on('click', function() {
var errors = [];
var html = '<ul>' ;
valid = true;
$('#errors').empty();
if ($('#editor').val() == '') {
errors.push('<li>please enter your article body</li>');
valid = false;
}
if ($('#ArticleTitle').val() == '') {
errors.push('<li>please enter your article title</li>');
valid = false;
}
if (!valid) {
html += errors.join('') + '</ul>'
$('#errors').append(html);
}
else{
$('#errors').hide();
}
return valid;
});
DEMO
I'm trying to use tinymce's getContent() to make a custom validation rule, how can I do this with jquery validation? I need to apply the rule to a textarea formatted with tinymce.
Validation: http://bassistance.de/jquery-plugins/jquery-plugin-validation/
$("#element").click( function(e) {
console.log(tinyMCE.activeEditor.getContent());
$("#someForm").validate({
rules: {
title: {
required: true
}
}
});
});
I'm thinking of just using a little bit of javascript with getContent() because it looks like there's just as much effort creating a workaround to get jquery validation working with tinymce. Thoughts on possible solutions?
The following stackoverflow questions should help you on that issue:
validating multiple TinyMCE Editor
Jquery validation form with TinyMCE field who gives no error by empty value
Hi if your are not getting client side validation on form submit time when you are with tinymce try this code
suppose your have two html editor 1 is txtAboutCompanyand 2 is txtProductinfo
this is client side code
<div class="divclass">
#Html.LabelFor(model => model.txtAboutCompany, new { #class = "required" })
#Html.EditorFor(model => model.txtAboutCompany)
<span class="field-validation-error" id="AC" style="margin:9px 0 0 157px;"></span>
</div>
this is jquery
$("#BusinessProfile").click(function () {
var aboutC = $("#txtAboutCompany").val()
var pinfo = $("#txtProductinfo").val();
if (aboutC == "" && pinfo == "") {
$("#AC").append("").val("").html("Please enter about company")
$("#PI").append("").val("").html("Please enter product information")
$("#bpform").valid();
return false;
} else if (aboutC == "") {
$("#PI").append("").val("").html("")
$("#AC").append("").val("").html("Please enter about company")
$("#txtAboutCompany").focus();
$("#bpform").valid();
return false;
} else if (pinfo == "") {
$("#AC").append("").val("").html("")
$("#PI").append("").val("").html("Please enter product information")
$("#txtProductinfo").focus();
$("#bpform").valid();
return false;
}
else {
$("#AC").append("").val("").html("");
$("#PI").append("").val("").html("");
//return true;
$("#bpform").validate();
}
});
you can get your all required validation on form submit time
I know this is not proper way but you can do it .
function tinymceValidation() {
var content = tinyMCE.activeEditor.getContent();
if (content === "" || content === null) {
$("#questionValid").html("<span>Please enter question statement</span>");
} else {
$("#questionValid").html("");
}
}
tinymce.activeEditor.on('keyup', function (e) {
debugger;
tinymceValidation();
});
$(form).submit(function (e) {
tinymceValidation();
});