Calling jQuery search on tab click - javascript

I have a jQuery search script that uses tabs for the user to define which search type they want to use. However, when the user searches for something and then selects a new search type (clicks on a tab) they have to go to the text box and press enter to submit their query again.
I want to call a the search when the user clicks on the tab of their choice, without them having to resubmit the query. How can I do this? I hope you can understand what I'm trying to describe.
My current jQuery code is:
$(document).ready(function(){
$("[id^=t_]").click(function(){
t=this.id.replace("t_","");
$("[id^=t_]").removeClass("s");
$("#t_"+t).addClass("s");
return false
});
$("#t_search").click();
$("form").submit(function(event){
event.preventDefault();
if($("#s").val().length>0){
q=$("#s").val();
$.ajax({
type:"GET",
url:""+t+".php?q="+q,
dataType:"html",
success:function(c){
$("#r").html(c);
$("#r").show()
}
});
}
});
});
My current HTML code is:
<div id="n">
All
Images
Videos
News
</div>
<form action="search" method="get">
<input type="text" id="s" name="q" maxlength="2048" autocomplete="off">
</form>
<div id="r"></div>

submit the form when the tab is changed:
$("[id^=t_]").click(function(){
t=this.id.replace("t_","");
$("[id^=t_]").removeClass("s");
$("#t_"+t).addClass("s");
if ($("#s").val()!="") { // only when there's a search term
$("form").submit();
}
return false
});

Try something like this...
You've already done half of the task.
$(document).ready(function(){
$("[id^=t_]").click(function(){
t=this.id.replace("t_","");
$("[id^=t_]").removeClass("s");
$("#t_"+t).addClass("s");
q=$("#s").val();
if($("#s").val().length>0){
q=$("#s").val();
$.ajax({
type:"GET",
url:""+t+".php?q="+q,
dataType:"html",
success:function(c){
$("#r").html(c);
$("#r").show()
}
});
}
return false
});
});

Related

multiple submit buttons only first initializes javascript

I'm echoing the Submit Button as seen below in each row of a Table. When clicked the Submit Button the Javascript initializes and alert()'s the response. The issue is only the first Button works as intended and subsequent buttons redirect to foobar.php.
Submit Button:
<form name="savefilenote" id="savefilenote" method="post" action="forbidden-savefilenote.php?notetype=2">Note: <input id="filenote" name="filenote" type="text" value="'.$filenote.'"> <input id="filename" name="filename" type="hidden" value="'.$filename.'"> <input type="submit" value="Save"></form>
Javascript:
<script>
$(function(){
$('.savefilenote').on('submit', function(e){
// prevent native form submission here
e.preventDefault();
// now do whatever you want here
$.ajax({
type: $(this).attr('method'), // <-- get method of form
url: $(this).attr('action'), // <-- get action of form
data: $(this).serialize(), // <-- serialize
beforeSend: function(){
$('#result').html('');
},
success: function(data){
$('#result').html(data);
if(data === "0") {
alert("foo");
}
if(data === "1") {
alert("bar");
}
}
});
});
});
</script>
Use a class instead of an id.
$("#savefilenote") can find only one instance of a button since and ID works for a specific element. If you change it to $(".savefilenote") and apply the same class to all buttons it should work.
id should be specific to a single element. Using the same id to identify multiple tags, you'll end up only affecting the first element in the body. If you want to associate a behavior to a group of elements, you'll need to use a class.

Trigger click once when page is loaded

I have a form in my page like so:
<form id="shipping" action="some-action-url" method="post">
<ul>
<li>
<input id="ship238280" name="method" value="238280|479435" type="radio" checked="checked">
<label for="ship238280">Transport (€0,00)</label>
</li>
<li>
<input id="ship292259" name="method" value="292259|580109" type="radio">
<label for="ship292259">Pick up (€0,00)</label>
</li>
</ul>
</form>
I'm using a SaaS platform so I have limited access to scripts and need to make use of what's actually available. So I'm looking for more of a workaround....
In above form I have checked the first option. To actually set the first shipping option I have to submit the form. Then in the system this option is set.
So I have a function that submits the form:
function sendform(){
var loader = $('.cart-loader');
var form = $('#shipping');
$(loader).show()
$.ajax({
type: "POST",
url: $(form).attr('action'),
data: $(form).serialize(),
success: function(data) {
$(loader).hide()
//$(this).unbind()
}
});
}
And a click event for when I click one of the options:
$('#shipping input').on('click', function(){
sendform()
});
What I want now is to submit the form on page load. So I have created something like this:
$(function(){
$('#shipping input').each(function(){
if($(this).is(':checked')){
$(this).trigger('click') // or sendform()
}
});
});
What happens now is that the form keeps submitting because everytime the page reloads (after submit) it wants to submit again!
How can I work around this knowing that it needs to submit first to set the option?
I tried things like $(document).one('ready', function(){ or something like $(this).unbind() in ajax success function.
I'm a bit lost :) So any help greatly appreciated!!
Try something like this: https://jsfiddle.net/noidee/uvm6jw3b/
$(document).ready(function(){
if( localStorage.getItem('submited') !== '1' ){
$('#myform').submit();
localStorage.setItem('submited', '1');
}
});

Jquery php Live search text disappears in search bar

I am new to jquery and am trying to make a live search from my existing search page where you have to press enter.
This is the code I have made so far.
$( document ).ready(function() {
$('#searchhh').on("input", function() {
var searchquery = this.value;
$( "#searchform" ).submit();
});
});
This gets the input of the form and searches it every key stoke. The problem is the text that the user types resets every time the form submits. I tried to post the search value as a get variable and display it as the search bars value and auto focus into the the search bar every time the page reloads, this puts the typing bar at the beginning of the form before what the user has typed.
I feel like I am approaching this the wrong way please help. :)
You need to post your form via ajax. Here's a simple fiddle to demonstrate this:
http://jsfiddle.net/e76d09vw/
HTML:
<form id="searchform" method="post" action="some_url_here">
<input type="text" name="search" placeholder="Search..." />
</form>
Results:<br>
<div id="results"></div>
JS:
$('#searchform').on("keyup", "input", function() {
var form_data = $("#searchform").serialize();
var form_url = $("#searchform").attr("action");
var form_method = $("#searchform").attr("method").toUpperCase();
$.ajax({
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnOutput){
// Your search results are outputted here
$("#results").html(returnOutput);
}
});
});

Using Javascript to send a keystroke in an input when a button is clicked

Is there any way using Javascript to send the "enter" aka keystroke "13" in an input when a button is clicked?
Details on why I want this:
Basically I have a car part look up tool that uses jQuery to actively post to a php file that searchs a MySQL DB, I wanted to make a few buttons with common car part OEMs, like; Chevrolet, Ford, Toyota etc.. I have the buttons doing they're thing when I click on them then change what is in the search field but it won't post to the php file until I press enter, so I wanted to hit two birds with one stone, click the button and it will enter 'chevrolet' in the search in put and then press enter for me all at once with one click of a button. =)
here is the code I am using to post data to the php file:
$(document).ready(function() {
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "search.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}return false;
}
$("input#search").live("keyup", function(e) {
clearTimeout($.data(this, 'timer'));
var search_string = $(this).val();
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}else{
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
});
UPDATE:
I was able to make it work with the following code:
Javascript:
$(".btn3").click(function() {
var e = $.Event('keyup');
e.which= 13;
$('#search').val($(this).val());
$('#search').trigger(e);
});
HTML:
<input type="button" class="btn3" id="CHEVROLET" value="CHEVROLET" />
I'm assuming you have a function that handles the event of a user pressing the 'enter' key in the search input. Simply give that function a name and have it fire on the button click as well!
The way to do what you are asking:
$('#buttonID').click(function(){
// Create a new jQuery.Event object with 'keydown' event specified.
var e = jQuery.Event( "keydown", { keyCode: 13 } );
// trigger (send) an artificial keydown event with keyCode 13
jQuery( "body" ).trigger( e );
});
Depending on the application, if it is to make it so that the form submits when a non-submit button is pressed then
$('#buttonID').click(function(){
$('#FormID').Submit();
});
would be the way to go.
Edit:
Alternatively to send the 'enter' command to the specific input box use:
$('#myInputId').trigger(jQuery.Event('keypress', {which: 13}));
You may need to replace which with keyCode depending on the version of jQuery you are using...
JSFiddle Demo
from the updated description though, sounds like there must be a form on the page, if you can determine its id (look through source for <form .. id="FormID" then it would be better practice to use the submit function as above:
$('#buttonID').click(function(){
$('#myInputID').val("Chevrolet"); // or however you are already doing this part
$('#FormID').Submit();
});
What you should do is split the Javascript from the button so your final result will be something like:
<script>
$(".btn3").click(function() {
$('#search').val($(this).val());
$('#search').trigger(jQuery.Event('keypress', {which: 13}));
});
</script>
<input type="button" class="btn3" id="Chevrolet" value="Chevrolet" />
<input type="button" class="btn3" id="Ford" value="Ford" />
<input type="button" class="btn3" id="Anotherone" value="Anotherone" />
What may be going wrong is you said you have multiple buttons, but keywords is a pretty generic id, which you may be repeating.. an ID must be unique or JS will not work correctly, if you want to perform a JS function for a group of things it is better to use the class, as this does not have to be unique.
so basically what the above does is waits for anything with class="btn3" in it to be clicked.
when that happens the input with id="search" gets filled with whatever the value= contains for what was clicked. Once that has happened the [enter] keypress is triggered inside the search input box.
This way, no matter which button gets pressed (Chevrolet, Ford or Anotherone) the search input box will get filled with the correct value. To add more buttons all you have to do is make sure they have class="btn3" and value="SOMETHING" and the above should work.
$(document).ready(function() {
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "search.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}return false;
}
$("input#search").live("keyup", function(e) {
clearTimeout($.data(this, 'timer'));
var search_string = $(this).val();
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}else{
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
// ADD THIS
$(".btn3").click(function() {
$('#search').val($(this).val());
search();
});
});
...
<!-- Fix inputs -->
<input type="button" class="btn3" id="Chevrolet" value="Chevrolet" />
<input type="button" class="btn3" id="Ford" value="Ford" />
<input type="button" class="btn3" id="Anotherone" value="Anotherone" />

Modal box + checkbox + cookie

I would like to achieve the following:
On homepage load, display modal box
Within modal box, display a form with a single mandatory checkbox
On checking the checkbox, hit submit and close the modal box, proceed to homepage
Remember this checkbox tick preference using a cookie
On a users return to the homepage, if they have checked the checkbox,
the modal box won't display
I've been getting somewhere with this:
http://dev.iceburg.net/jquery/jqModal
In that I can get the modal box displaying on page load, but I can't work out how to get the form to make the checkbox mandatory and close the box. I also don't know where to start when setting a cookie.
Any pointers would be much appreciated.
Thanks
EDIT: to include code:
Index.html - to display modal box on page load
$().ready(function() {
$('#ex2').jqm({modal: 'true', ajax: '2.html', trigger: 'a.ex2trigger' });
setTimeout($('#ex2').jqmShow(),2000);
});
2.html - modal box content loaded via ajax
function validate(frm) {
if (frm.checkbox.checked==false)
{
alert("Please agree to our Terms and Conditions.");
return false;
}
}
<form action="" method="POST" onSubmit="return validate(form);" name="form">
<input type="checkbox" name="checkbox" id="checkbox" value="1"> I hereby agree to all Terms and Conditions</a>
<input type="submit" value="Submit">
</form>
Load the jquery cookie plugin to allow to set/read cookies: http://plugins.jquery.com/project/cookie
then.. something like this below. Untested, but you get the idea
index.html:
$().ready(function() {
if (!$.cookie('agreed_to_terms'))
{
$('#ex2').jqm({modal: 'true', ajax: '2.html', trigger: 'a.ex2trigger' });
$('#ex2').jqmShow();
}
});
2.html:
$().ready(function()
{
$('#agreeFrm').submit(function(e)
{
e.preventDefault();
if ($(this).find('input[name=checkbox]').is(':checked'))
{
$.cookie('agreed_to_terms', '1', { path: '/', expires: 999999 });
$('#ex2').jqmHide();
}
});
});
<form id="agreeFrm" action="" method="POST" name="form">
<input type="checkbox" name="checkbox" id="checkbox" value="1"> I hereby agree to all Terms and Conditions</a>
<input type="submit" value="Submit">
</form>
I used a JQuery plugin not long ago called SimpleModal
I was very impressed with how easy it was. On the modal I had multiple checkboxes and to carried the values of the checkboxes back to the page the modal was on after a submit button was hit.
All the info and demos are on the SimpleModal homepage
It works, finally!
I was missing the callback when the cookie exists and these tics '' around the value of the cookie.
Here is how it looks like. Please, let me know if there is some obvious mistake.
(many thanks for your support)
function confirm(msg,callback) {
$('#confirm')
.jqmShow()
.find('p.jqmConfirmMsg')
.html(msg)
.end()
.find(':submit:visible')
.click(function(){
if(this.value == 'Proceed'){
$.cookie("agreed_to_terms", '1', { expires : 1, path: '/' }); //set cookie, expires in 365 days
(typeof callback == 'string') ?
window.location.href = callback :
callback();
}
$('#confirm').jqmHide();
});
}
$().ready(function() {
$('#confirm').jqm({overlay: 88, modal: 'true', trigger: false});
// trigger a confirm whenever links of class alert are pressed.
$('a.confirm').click(function() {
if ($.cookie('agreed_to_terms') == '1'){window.location.href = callback =
callback()
//they already have cookie set
}else{
confirm('About to visit: '+this.href+' !',this.href);
}
return false;
});
});// JavaScript Document

Categories

Resources