Alert message if search query is not more then x characters - javascript

First, thanks for taking the time to look at my question. Really. This is my question. I'm making a fancybox search page for a website I'm making. Getting the search results in fancybox all work fine.
But if the visitor just clicks on search it returns every item on the site. What I would like is make the form so, that the visitor has to at least enter 3 characters before the search does a search. If the visitor doesn't enter 3 or more characters fancybox will give an alert saying please enter at least 3 or more characters.
I've looked around stackoverflow and found this code:
$( document ).ready(function() {
input_value = $.trim($('#searchkey').val());
if(input_value == ''){
alert('Enter some value');
return false; //Does not submit the form
}else{
//perform your code if it should not be empty.
}
});
So I placed my code inside the correct place, like so:
$( document ).ready(function() {
input_value = $.trim($('#str').val());
if(input_value == ''){
alert('Enter some value');
return false; //Does not submit the form
} else {
$(function() {
$('#search').on('submit', function(e) {
e.preventDefault();
jQuery.fancybox({
width: 600,
height: 600,
openEffect: 'fade',
closeEffect: 'fade',
href: 'search-post-results.php',
type: "ajax",
ajax: {
type: "POST",
data: {
value: $('#str').val()
}
}
});
});
});
}
});
I'm not getting any syntax errors, but if I reload the page it gives me the correct alert. But thats if there are no characters entered. So I've changed this line:
if(input_value == ''){
to:
if(input_value == '2'){
Figuring that I should set a value. But that does nothing. Does anyone have a similar script/snippet that does the same? Or know why this isn't working?
Here is the HTML (nothing special there):
<form id="search">
<table>
<tr>
<td>
<input type="text" name="s" id="str" placeholder="Search...">
</td>
<td>
<button class="btn form-button btn-default">
<i class="fa fa-search"></i>
</button>
</td>
</tr>
</table>
</form>
Thans again for your time.

Use length property.
if( input_value.length < 3 ){
// error message if characters are less than 3
} else {
// continue the search
}

Try this ,
Also Please change validation position because if you reload then always alert will show . So you can validate after submit action.
$(function() {
$('#search').on('submit', function(e) {
e.preventDefault();
if(input_value.length < 3 ){
// Show your alert message.
}else{
// Here you start Ajax Request.
}
});
});

Related

button onclick call javascript function not working

Im trying to call a function when user clicks on the navbar search button but it does not seem to call the javascript fuction and just loads the same page. I have looked at examples and other questions but I dont see anyhing wrong.. Any help would be much appreciated, Here is my code, It is in my Masterpage.aspx:
<div class='navbar-form navbar-left' role='search'>
<div class='inputgroup'>
<input class='form-control' id='navinput' type='text' placeholder='Search'/>
<button class='btn btn-default' type='submit' id='navsearchbtn' runat='server' onclick='NavToSearch();'>
<span class='glyphicon glyphicon-search'></span>
</button>
</div>
</div>
Here is my Js code (also in Masterpage.aspx): I just have the test redirect to see if it works. (The code that i want to implement is in comments please check that is okay as well, I then want to use the input text to search database)
<script type='text/javascript'>
function NavToSearch() {
window.location.href = 'Search.aspx';
/*var navsearchText = $('$navinput').text();
if (navsearchText == '')
{
$('$navinput').attr('placeholder', 'Enter Search Text');
return false;
}
else window.location.href = 'Search.aspx'; */
}
</script>
UPDATED script/function:
<script type='text/javascript'>
function NavToSearch()
{
var navsearchText = $('#navinput').text();
if (navsearchText == '')
{
$('#navinput').attr('placeholder', 'Enter Search Text');
return false;
}
else {
window.location.href = 'Search.aspx';
//return false;
}
/*OR
$(document).ready(function(){
var url = "OrderHistory.aspx";
$(location).attr('href',url);
})*/
}
</script>
If youwant just to call the NavToSearch() when the button clicked you have to change the type of the button from submit to button :
<button class='btn btn-default' type='button' id='navsearchbtn' runat='server' onclick='NavToSearch();'>
<span class='glyphicon glyphicon-search'></span>
</button>
In your commented code you have to replace $ sign by # for the id navinput and also .text() by .val() :
$('#navinput').val();
Instead of :
$('$navinput').text();
Hope this helps.
Sounds like you are using Asp.net Web Forms, if true, your page will have a form element, then for a button with type=submit will trigger the form submit by default, generally this will redirect to your current page.
You can avoid this by return false in the click handler:
function NavToSearch() {
window.location.href = 'Search.aspx';
/*var navsearchText = $('$navinput').text();
if (navsearchText == '')
{
$('$navinput').attr('placeholder', 'Enter Search Text');
}
else window.location.href = 'Search.aspx'; */
return false; //prevent the form submit whatever.
}
For a submit button, either the form submission will cancel the redirect, or the redirect will cancel the submission if return false is added after.
Check this question:
How do I redirect users after submit button click?

Form submit with 2 different errors depending on input value - 1 is not working

I posted a question on how to make 2 errors work here: Multipile forms with input and submit button with the same action with Javascript
I needed 2 errors, 1 error if the input if less than 15 digits, the second error is if the input begins with 9900 (if it does, there is an error and then it redirects to a different page).
It worked for a while, although suddenly it stopped giving the second error (if input starts with 9900), the page is: http://www.unlocker.co.il/shop/sim-unlock-htc-mobile-device/
Each form has it's own id: unlock1, unlock2, unlock3 etc.
the JS files include:
jQuery(function($){
$('form#unlock1').on('submit', function (e){
if($('form#unlock1 > input.the_imei').val().length == 15){
if($(this).val().indexOf('9900') === 0){
alert('לפי המספר IMEI, ברשותכם מכשיר CDMA, אנא ראו מידע נוסף בעמוד פתיחת מכשירי CDMA');
window.location = 'http://www.unlocker.co.il/sim-unlock-cdma-mobile-device';
e.preventDefault();
}
return;
}
alert('אנא מלאו מספר IMEI בעל 15 ספרות');
e.preventDefault();
});
})
and the Forms are:
<form id="unlock1" class="cart" enctype="multipart/form-data" method="post" name="unlock"> <input class="the_imei" style="width: 80%; border-radius: 15px;" name="the_imei" type="text" value="" placeholder="מספר סידורי IMEI של המכשיר (חייג #06#*)" /> <input class="add-to-cart" name="add-to-cart" type="hidden" value="39" /> <button class="unlockButton" type="submit" value="submit">פתח לכל הרשתות בישראל </button> </form>
Each form has a different id (example Unlock1) and on it's own JS file the id like listed in 2 places.
I can't figure out why the "minimum 15 digits" error works, but the "if input begins with 9900" error does not work anymore.
Thanks!
This is how I would do this. Try to avoid using too many nested if statments. Instead create the escape clauses with return statements when the user enters the incorrect value first.
$('form#unlock1').on('submit', function(){
var $el = $('form#unlock1 > input.the_imei');
if($el.val().length<15){
//Not enough characters
return false;
}
if($el.val().substring(0,4)=='9900') {
//Value begins with 9900
return false;
}
//User has entered a correct imei
});

Javascript form action

i have a text field on my page that has an autocomplete featuring items from a database. When selected this scrolls the page using jquery to where that result is on the page. I want the form to scroll to the result on submit button instead of having to click the text field again. How would i edit my code so that it happens on submit, rather than on text field click
form code -
<form autocomplete="off">
<form name="search-highlight" id="search-highlight" method="post" action="#">
<p>
Film Name <label>:</label>
<input type="text" name="scroll" id="scroll" class="scroll"/>
<!--input type="button" value="Get Value" /-->
</p>
<input type="submit" value="find" />
</form>
and the javascript
$("#scroll").autocomplete("get_film_list.php", {
width: 260,
matchContains: true,
//mustMatch: true,
//minChars: 0,
//multiple: true,
//highlight: false,
//multipleSeparator: ",",
selectFirst: false
});
$("#scroll").click(function(){
// start variables as empty
var scroll = "";
var n = "0";
// hide the results at first
$("p.results").hide().empty();
// grab the input value and store in variable
scroll = $('#scroll').attr('value');
console.log("The value of film is: "+scroll);
$('span.highlight').each(function(){
$(this).after($(this).html()).remove();
});
if($('#scroll').val() == ""){
$("p.results").fadeIn().append("Enter film in field above");
$('#scroll').fadeIn().addClass("error");
return false;
}else{
$('div.timeline :contains("'+scroll+'")').each(function(){
$(this).html($(this).html().replace(new RegExp(scroll,'g'), '<span class="highlight">'+scroll+'</span>'));
$(this).find('span.highlight').fadeIn("slow");
var offset = $(this).offset().top
$('html,body').animate({scrollTop: offset}, 2000);
return false;
});
// how many did it find?
n = $("span.highlight").length;
console.log("There is a total of: "+n);
if(n == 0){
$("p.results").fadeIn().append("No results were returned");
}else{
$("p.results").fadeIn().append("<strong>Returned:</strong> "+n+" result(s) for: <em><strong>"+scroll+"</strong></em>.");
}
return false;
}
});
});
I hope you understand my problem - if not heres a demo (not optimized) www.ignitethatdesign.com/CheckFilm/index.php
DIMENSION
If you change the $("#scroll").click( to target the submit button (something like $("#search-highlight input[type='submit'].click) should get you the behavior.
You should probably expand the signature of your click callback to include an event argument, as in
.click(function(event)){ so later on you can call event.stopPropagation(), to indicate to the browser the click event on your input has been handled (and it doesn't try to post the form back).

jQuery validate before page reload

So when I click submit it directs to error page. I'd like to validate before it redirects to error page, the plugin works like that. Is there a way to prevent the submission if there was something wrong with the user's input ?
<input type="submit" name="submit-contact" class="button" value="Send" />
$(document).ready(function(){
$(".button").click(function() {
var name = $('input#name').val();
if (name == ""){
$('#name').addClass('errro');
return false;}
else {
$('#name').removeClass('errro');}
});
});
After several minutes of staring at the question I think I know what you mean. You can do that by listening for the submit event and returning false when you think that there's something wrong with the user's input.
$(document).ready(function(){
$("#theForm").submit(function() {
var name = $('input#name').val();
if (name == ""){
$('#name').addClass('errro');
return false;
}
else {
$('#name').removeClass('errro');
}
});
});
input type="submit" name="submit-contact" class="button" onClick="Somejavascriptfunction" value="Send"
function Somejavascriptfunction()
{
Retrieve Username and password via $(".Username").val() and $(".Password").val()
Pass it to a ajax request page.
Get result back from ajax page.
If invalid then pop up message via jquery
if valid then submit.
}
AjaxPage
{
Do the verification(1. Empty username/password 2. Correct username and password..etc)
Return result back to calling function
}

Pressing 'enter' on a input type="text", how?

I am facing a problem I can not solve JQuery Javascript. Can you help me and help me understand.First here is my code :
(...)
<script type="text/javascript">
// Autocomplete suggestions
$(function () {
$("#autoCompInput").autocomplete({
source: "/Suggestions",
minLength: 3,
select: function (event, ui) {
if (ui.item) {
$("#autoCompInput").val(ui.item.value);
$("form").submit();
}
}
});
});
// Provide search results
$(function () {
$("#autoCompSearch").click(function () {
var searchParameters = $("#autoCompInput").val();
var jsonData = JSON.stringify(searchParameters, null, 2);
window.location = "/Search?criteria=" + searchParameters;
});
});
</script>
(...)
<input class="ui-autocomplete-input" id="autoCompInput" role="textbox" aria-haspopup="true" size="50" autocomplete="off" aria-autocomplete="list" value = "#ViewBag.SearchInfo"/>
<a id= "autoCompSearch" href = "#" ><img src="#Url.Content("~/Content/Menu/Images/magnifier.png")" alt="Search" /></a>
(...)
With this code I can't use the 'Enter' key to execute my search. When the user is in the input autoCompInput I would like to be able to detect if he press 'enter' and launch the submit. I read I must add a onkeyup="onKeyPressed(event)" event but I don't understand how to write the javascipt associated with the command. I tried but without success... Do you have a solution for me?
Thank you,
You should bind the keypress event to your input
$("#autoCompInput").bind("keypress", {}, keypressInBox);
function keypressInBox(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) { //Enter keycode
e.preventDefault();
$("yourFormId").submit();
}
};
With similar HTML:
<input type="text" id="myTxt" />
<input type="submit" id="mySubmit" />
This script (which uses the latest jQuery 1.7.2) should do it:
$('#mySubmit').click(function() {
alert('Submitted!');
return false;
});
$('#myTxt').on('keyup', function(e) {
if (e.keyCode === 13) {
$('#mySubmit').click();
}
});
Here's a working example.
To assign a keyup event in jquery
$("#autoCompInput").keyup(function(event) {
if (event.keyCode==13) {
alert('enter key');
}
});
I think there is a better and more standard solution to this type of problem.
you can have a GET form around those inputs and whenever you press enter on any input inside that form, it will be submitted to whatever is in the action attribute of the form. This is how it would look like (I took your code but I am removing the bits irrelevant for my answer):
<form id="idForJqueryOnly" action="/Search" method="GET">
<input type="text" name="criteria" value="someuserinput"/>
<button type="submit"><img src="...")" alt="Search" /></button>
</form>
This is standard browser behaviour. So, what the form does? when submitted the browser creates a URL like this:
http://yourserverguesedfromthecurrenturl/Search?criteria=someuserinput
What happened is that the browser took all the inputs with name and value (and not disabled) from the form and serialized them into url form.
Now, the submit event can be triggered by pressing enter on any of the inputs inside, including buttons as long as the buttons don't have the attribute type="button".
If you wanted to do more things with the data with javascript before going to the search page, you can do this with jquery:
$("#idForJqueryOnly").submit(function(){
// here you can do stuff like serialize the form, or sanitize the input of tue user.
var data = $("#idForJqueryOnly").serialize();
$("[name=criteria]").val($("[name=criteria]").val().customSanitizeMethod());
// if you return false, the form will not submit, say, for validation errors:
return customValidator.isFormValid("#idForJqueryOnly");
})

Categories