Jquery php Live search text disappears in search bar - javascript

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);
}
});
});

Related

Javascript populates input, but not span?

I am using Select2 dropdown menu to get data from database threw ajax and json/php.
The option i make will then populate some input fileds for editing the database.
I use (This field get´s populated ok):
<input type="text" class="form-control" name="valt_element_id" id="valt_element_id" placeholder="Objekt ID" />
But on some field i just want to show the data, not to be edited.
I figured to use:
<span id="valt_element_id"></span>
But this span code won´t work!
Why?
JS:
$(document).ready(function(){
var valtObjektElement = $('#valj_objekt_element');
$('#valj_objekt_element').select2({
ajax: {
url: "valj_objekt_element.php",
dataType: 'json',
data: function (term, page) {
return {
q: term
};
},
results: function (data, page) {
return { results: data };
}
} // Ajax Call
}); // Select2
// Start Change
$(valtObjektElement).change(function() {
var ElementId = $(valtObjektElement).select2('data').id;
var ObjektNummer = $(valtObjektElement).select2('data').text;
$('#valt_element_id').val(ElementId);
$('#valt_objekt_nummer').val(ObjektNummer);
}); //Change
}); //Domument Ready
There is no value attribute for span. You should either use text or html.
Replace
$('#valt_element_id').val(ElementId);
with
$('#valt_element_id').text(ElementId);
Using javascript:
document.getElementById("valt_element_id").innerHTML = ElementId;
Or jQuery:
$('#valt_element_id').html(ElementId);
You mentioned:
But on some field i just want to show the data, not to be edited . Why not use readonly attribute in input rather than replacing it with a span ?

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" />

Create URL upon JavaScript submit form

I currently have a form with some JavaScript functions and localstorage.
I'm trying to get that when a user types a value into a textbox, the search bar changes the URL from "mysite.com" to "mysite.com/%userinput%". Then that user can send that link to someone else and that person will then see what the original user saw.
This will change the URL after input.
As I understand from your question and comments, you don't want to load the URL, just change it, so try this fiddle: http://jsfiddle.net/GrP6U/2/show/
The code behind is:
JavaScript
var theForm = document.getElementById('theForm');
var theInput = document.getElementById('subj');
theForm.onsubmit = function(e) {
var myurl = "http://jsfiddle.net/GrP6U/2/show/?input=" + encodeURIComponent(theInput.value);
window.history.pushState('', "Title", myurl);
return false;
}
HTML
<form id="theForm">
<input id='subj'/>
<input type='submit'/>
</form>

JQuery Ajax call stop refresing the page

I have the following html code:
<div>
<form id="ChartsForm">
<div id="optionsheader">
<p>Choose your page:</p>
<div id="dateoptions">
<p>Until date: <input type="date" name="until_date" value="Until date"></p>
<p>Since date: <input type="date" name="since_date" value="Since date"></p>
</div>
</div>
<select name="accmenu" id="accmenu" style="width:300px; float:left; clear:both;">
<?php
$user_accounts = $facebook->api('/me/accounts','GET');
foreach($user_accounts['data'] as $account) {
?>
<option data-description="<?php echo $account['category'] ?>" data-image="https://graph.facebook.com/<?php echo $account['id']; ?>/picture" value="<?php echo $account['id'] ?>"><?php echo $account['name'] ?></options>
<?php
}
?>
</select>
<div class="insightsoptions">
<p>Choose your insights:</p>
<input id="newLikes" class="insightsbuttons" type="submit" name="submit" value="Daily new likes">
<input id="unlikes" class="insightsbuttons" type="submit" name="submit" value="Daily unlikes">
</div>
<div class="insightsgraphs">
<div id="dailyNewLikes"></div>
<div id="dailyUnlikes"></div>
</div>
</form>
</div>
which has a form with the id=ChartForm that contain two date inputs until_date and since_date, one select accmenu and two submit inputs with the values Daily new likes and Daily unlikes. I use the following Jquery function:
$(function () {
$('#accmenu').change(function() {
$(".insightsgraphs div").hide();
$(".insightsoptions input").attr("class","insightsbuttons");
});
$("#newLikes").one('click', function () {
$.ajax({type:'GET', url: 'newLikes.php', data:$('#ChartsForm').serialize(), success:
function(response) {
var json = response.replace(/"/g,'');
json = "[" + json + "]";
json = json.replace(/'/g,'"');
var myData = JSON.parse(json);
var myChart = new JSChart('dailyNewLikes', 'line');
myChart.setDataArray(myData);
myChart.setSize(960, 320);
myChart.setAxisNameX('');
myChart.setAxisValuesColorX('#FFFFFF');
myChart.setAxisNameY('');
myChart.setTitle('Daily New Likes');
myChart.draw();
}});
return false;
});
$("#newLikes").on('click', function(){
$(this).toggleClass('green');
$('#dailyNewLikes').toggle();
});
$("#unlikes").one('click', function () {
$.ajax({type:'GET', url: 'unlikes.php', data:$('#ChartsForm').serialize(), success:
function(response) {
alert(response);
$("#dailyUnlikes").html(response);
}});
return false;
});
$("#unlikes").on('click', function(){
$(this).toggleClass('green');
$('#dailyUnlikes').toggle();
});
});
for the application flow in the following manner: every time I click on one of the input submit buttons the script will make only one Ajax GET request to a specific php file that send me back a response with which I create a Chart in a hidden div with the id=dailyNewLikes or id=dailyUnlikes by case (for testing purposes I work for the moment only on the first button). The button it will change his background color into green and the div it will be shown. I use $("#newLikes").on('click', function(){ for change back and forth the background color and the display time of the div. (from green and display:block to red and display:none, you get the point I hope :D). Also I use $('#accmenu').change(function() { to change all buttons to red and hide the respective div in case an option from the select is changed. My problem is that after I refresh the page (Ctrl+R) choose since and until date, click on the first button (it change to green and the div is shown, also the toggle is working fine) and then click on the second button which works fine on the first click (is becoming green and div is shown) but on the second click I have an issue: the script is making another Ajax GET request (a wrong URL one) and the page is refreshed. Ex. of a good reguest URL:
http://localhost/smd/unlikes.php?until_date=2013-05-01&since_date=2013-04-01&accmenu=497232410336701
and an ex. of a wrong request URL:
http://localhost/smd/?until_date=2013-05-01&since_date=2013-04-01&accmenu=497232410336701&submit=Daily+unlikes#_=_
Like it can be seen (it doesn't need in the first to make this extra request) the php file is not present and also a new submit parameters is added. This also happen if I change from the select with another option. What am I do wrong? I really need to know, not just to have my code "fixed". It bugging me for a little while. Any feedback is more than welcomed. P.S. Also, how can I start the .one function only if both date inputs has been choosen? Something like how could help me?
var until = $('#dateoptions input[name="until_date"]').val();
var since = $('#dateoptions input[name="since_date"]').val();
if (until == "" || since == "") {
alert('Until date or Since date missing!');
return;
}
it will work that way? Sorry for the long question...
i think you should make your question a little shorter and just point what you need and what errors are you getting ..anyways...going through your code i see you have two click event for same button at the end for $("#unlikes").one and $("#unlikes").on(..and no return false in other function.
try adding return false
$("#newLikes").on('click', function(){
$(this).toggleClass('green');
$('#dailyNewLikes').toggle();
return false;
});
$("#unlikes").on('click', function(){
$(this).toggleClass('green');
$('#dailyUnlikes').toggle();
return false;
});
my guess is that , since you have two click event..when it gets clicked ..these event will fire and since you are missing return false in second click function...the form gets submitted hence refreshing the form.
however its better if put your codes in single click function than creating two seperate click event.

Calling jQuery search on tab click

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
});
});

Categories

Resources