I incorporated a jquery type-ahead autocomplete script into an existing search page that consisted of 2 dropdown auto submit search boxes. Those auto submits where accomplished using onchange and they were self referencing. As soon as the user selected the category in the first drop down, the page returned with the second drop down filled with an ever increasing number of options. The page submitted using the following code;
<form name="nav"><select name="platform" id="platform" onChange="document.location.href=document.nav.platform.options[document.nav.platform.selectedIndex].value">
Upon completion of the user selecting the first drop down, the page returns to itself and narrows the results for the second drop down. The problem was the second drop down was getting too big for users to maneuver.
Without knowing jquery I've been able to graft the type ahead autocomplete script into the existing search form for the replacement of the second drop down. However, I cannot figure out how to carry the value of the jquery search forward to the same page to have a php statement execute it.
The following jquery populates the second field with the id of the record I need to carry forward. This is the function from jquery;
<script type="text/javascript">
function lookup(inputString) {
if(inputString.length == 0) {
// Hide the suggestion box.
$('#suggestions').hide();
} else {
$.post("rpc.php", {queryString: ""+inputString+""}, function(data){
if(data.length >0) {
$('#suggestions').show();
$('#autoSuggestionsList').html(data);
}
});
}
} // lookup
function fill(thisValue) {
$('#inputString').val(thisValue);
setTimeout("$('#suggestions').hide();", 200);
}
</script>
This is the html at the bottom of the page that ends up containing the id of the record I need going forward.
<div>
<form name="dash3.php">
<div>
Start typing the name of the item, select the correct title when it appears:
<br />
<input type="text" name="papa" size="30" value="" id="inputString" onkeyup="lookup(this.value);" onblur="fill();" />
<input type="hidden" value="?list=1" />
</div>
<div class="suggestionsBox" id="suggestions" style="display: none;">
<img src="upArrow.png" style="position: relative; top: -12px; left: 30px;" alt="upArrow" />
<div class="suggestionList" id="autoSuggestionsList">
</div>
</div><input type="submit" value="Submit">
</form>
</div>
The php sitting at the top of the page is looking for this to trigger the add;
if ($_GET['list']==1) {
I need to set 'list' equal to 1 (you can see I tried that with the hidden input) and the php variable named $vid set to the contents of the jquery type ahead results so that the submit button will carry the values forward and the php script will execute the add. I've tried hidden fields, I've tried grafting pieces of jquery together but I don't have a solid base in java or jquery and I can't think of another way to do this. I've gotten a little further with each request, I hope that I've framed the question well enough to get it this go around! Thanks much.
From first glance, it looks like you are updating the "inputString" input with a null value on blur? You have not passed anything to your "fill" function.
JQuery provides simple event handlers that would clean that part up a bit.
$(function(){ // <--This waits until load to initialize handlers
$("#inputString").blur(function(){
alert($(this).val());
});
});
Related
I have situation where I have an accordian and I am referencing a php file gridlist.php within another php file displayvar.php. In other words the context of displayvar.php are shown in the webpage gridlist.php. Now gridlist.php has a checkbox input:
<input type="checkbox" id="foodlike" value="icecrm">I like ice cream</input>
<input type="checkbox" id="foodlike" value="pizza">I like pizza</input>
<input type="checkbox" id="foodlike" value="soda">I like soda</input>
Now when I check on the checkboxes in the table referenced by gridlist.php displayvar.php should be able to display a list of the items checked. For instance it should display if all three checkboxes are checked:
icecrmpizzasoda
If the last one is checked then only soda should be displayed. Keep in mind because this displayvar.php is displayed within the context of the website gridlist.php I used the following command in gridlist.php:
<?php include 'displayvar.php'; ?>
I tried in the displayvar.php to obtained the variables foodlike (as defined by the variable id in the checkbox gridlist.php) from gridlist.php and then echo them based on this snippet of code:
<?php
$like=$_POST['foodlike'];
echo "$like";
?>
How can I tweak this code to get my desired result?
You can achieve this with :
gridlist.php
<form method="post" action="displayvar.php">
<input type="checkbox" name="icecrm" value="icecrm">I like ice cream</input>
<input type="checkbox" name="pizza" value="pizza">I like pizza</input>
<input type="checkbox" name="soda" value="soda">I like soda</input>
<input type="submit" value="Submit">
</form>
displayvar.php
<?php
$icecrm = isset($_POST['icecrm']) ? $_POST['icecrm'] : null;
$pizza = isset($_POST['pizza']) ? $_POST['pizza'] : null;
$soda = isset($_POST['soda']) ? $_POST['soda'] : null;
echo is_null($soda) ? $icecrm.$pizza : $soda;
?>
As you mentioned you did not want a submit button, you'll probably want some sort of "interactive", instant solution and bypass going to the server, i.e. bypass PHP. Since the include 'foo.php'-statement effectively dumps all contents of foo.php into the current file (you could say it "merges them into one"), all interactions happen on the same page. Thinking about your setup as "file A is communicating with file B via the server" is wrong - there is only one file/page.
So, having said all this, my proposed solution uses Javascript and the seemingly omni-present jQuery library, which you will have to include in your page. The snippet below binds an event-handler to the inputs' change-event, which is triggered when a checkbox or radio are checked or the value of a text-input is changed. Then, we append the checked value to a dummy container for display.
$(function() {
var $likes = $('#likes');
// bind event handler to all input-elements
$('input').on('change', function() {
var $input = $(this),
oldText = $likes.text();
if ($input.is(':checked')) {
$likes.append($input.val());
} else {
$likes.text(oldText.replace($input.val(), ''));
}
});
});
label {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="icecream">
<input type="checkbox" name="icecream" id="icecream" value="icecrm">I like ice cream</label>
<label for="pizza">
<input type="checkbox" name="pizza" id="pizza" value="pizza">I like pizza</label>
<label for="soda">
<input type="checkbox" name="soda" id="soda" value="soda">I like soda</label>
<span id="likes"></span>
Edit: This is how I would lay out the "root" file containing the two gridlist.php and displayvar.php, along with the Javascript required to manipulate the DOM:
<html>
<head>
<title>Test</title>
<style>
label {
display: block;
}
</style>
</head>
<body>
<!-- This will be in a file you called 'gridlist.php' -->
<label for="icecream">
<input type="checkbox" name="icecream" id="icecream" value="icecrm">I like ice cream</label>
<label for="pizza">
<input type="checkbox" name="pizza" id="pizza" value="pizza">I like pizza</label>
<label for="soda">
<input type="checkbox" name="soda" id="soda" value="soda">I like soda</label>
<!-- // -->
<!-- This will be in a file you called 'displayvar.php' -->
<span id="likes"></span>
<!-- // -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var $likes = $('#likes');
// bind event handler to all input-elements
$('input').on('change', function() {
var $input = $(this),
oldText = $likes.text();
if ($input.is(':checked')) {
$likes.append($input.val());
} else {
$likes.text(oldText.replace($input.val(), ''));
}
});
});
</script>
</body>
</html>
Edit 2:
You still seem to be having problems, so I shall try to clarify why I think you are not succeeding.
Using only PHP, it is not possible to access the value of a checked checkbox without submitting the form back to the server.
To retrieve the value of a checkbox that has been checked by the user, you essentially have only two possibilities.
Option 1: Submit the form using POST/GET
This entails you having a <form> element enclosing the inputs along with a submit button for submitting the form. This is how (probably) 98% of forms on the Internet work. The data in the form is sent, using either the POST or GET method, to the script you specify in the form-tag. Consider this as an example (text omitted):
<form action="handler.php" method="get">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<button type="submit"></button>
</form>
When the user clicks the submit-button, the form is sent to handler.php via the GET method. There, the form data will be available in the $_GET array. Same applies for POST. Now, an often-used approach is to submit the form to the same script via action="#", meaning you need not have a dedicated handler, but can process data within the same script as your form. Obviously, you will have to distinguish two cases: one initial case where no data is set in $_GET/$_POST, and one submission-case when the data is set.
The same applies to data stored in the $_SESSION, btw: again, you will have to tell a server-side script to put the data you want in the user-session; only then will you be able to retrieve it again.
A similar approach I would call "Option 1 b)" is submission via AJAX. This is basically form submission without leaving/reloading the page. Sending the data is done via Javascript and an "XMLHttpRequest". An XHR lets you send any type of data, not only XML. Again, similar logic applies: you serialize the data in some way, provide an endpoint, usually a script, to talk to, and communicate the data to that script via POST/GET. Then your script can handle the data and return a response, which will be available in the JS that initiated the AJAX-request.
Option 2: By accessing the DOM directly
The DOM is the "tree" that is made up of the HTML-elements of your page. Using Javascript, one can access and modify these elements, remove specific ones or add new ones. This API used to be implemented quite differently across browsers, which is why libraries like jQuery or Prototype were created: they provide a unified API across different user agents.
We can use two features of these libraries:
respond to (user-triggered) events
access elements and data stored therein
This is the approach I used in my answer, which I will not repeat here and you can read above. We respond to the event of the user clicking on a checkbox, and access that very checkbox to retrieve the value-data and process it further.
TL;DR
You have two options: submit the form to a script and process the data there; or, manipulate the DOM to catch user-events and pull out the values.
Credit: this is summing up every answer and comment in this thread, especially those of Obsidian Age and Valentin Papin, who both gave great answers that would lead to a clean and functional result.
I have a form table with checkboxes. I want the user to check whichever url (element) they want to delete, press a button which then calls a "delete.php" file which deletes that record in mysql.
What I am trouble finding out how to do is to call the delete.php file with a button outside of the form. I know that you would typically use a submit button inside the form but in this situation, I am exploring whether it is possible to do it with a button that is outside it.
An image is attached to illustrate why I want to do that. The url menu on the bottom is called by a function because I want it to be modular. So I think the "Delete BM" question needs to be able to action the deletion of the checked checkbox.
I have googled a variety of search cases which dont really answer my question:
How to send checkbox state through form in a table
Search "php how to call php file outside form"
Search "how to call php file without submit button"
Call php file without using form action
Submit without submit button
Use following code for submitting your form.
and use search keyword in google "submit form without submit button in php".
<form id="jsform" action="whatever you want">
// input fields
</form>
<script type="text/javascript">
document.getElementById('jsform').submit();
</script>
For Your Problem. Below are Sample code
<input type='checkbox' class='test' name='test' value='1'>
<input type='checkbox' class='test' name='test' value='2'>
<input type='checkbox' class='test' name='test' value='3'>
<input type='checkbox' class='test' name='test' value='4'>
is somthing your checkboxes then following is the script
<script>
$(function(){
$(".test").click(function(){
var checkBoxValue = $(this).val(); // value of checkbox
$.ajax(
{
url: "" // url of page where delete funcnality is written
// and id of field
})
.done(function(data)
{
// success
});
});
});
</script>
In the past I have come across this sort of issue, of wanting a submit button outside of a form for layout/presentation reasons.
Having given it some thought and reading around, I learned there were some very good reasons to avoid doing so;
Changing the default behaviours of the browser is generally a bad idea, you make extra work for yourself and in the end is likely to complicate things and often also lead to confusing users. (for example: what happens if user clicks enter, will it still submit the form?)
Users that do not have up to date javascript or do not have it switched on, will not be able to use your form / site.
You can achieve what you want and still use the standard html submit button. Using CSS to make it appear as a text link, great example;
How to make a submit button display as a link?
In your example I personally would just have the submit button appear as a button (styled to match sites design) directly under the checkboxes, separate from your menu below. As this makes the most sense to me, and would save you some work as you wouldn't need to fiddle with your menu function.
However if you wanted to achieve exactly as you set out, you could pass the button (html string) as a paramenter into your function so that it can be entered into the menu list, then return all the menu html string and print it inside your form;
<form>
<input type="checkbox" name="1" /><br />
<input type="checkbox" name="2" /><br />
<input type="checkbox" name="3" /><br />
<?php
$buttonHtml = '<input type="submit" name="delete_bm" value="delete bm" class="submitLink" />';
echo navMenu($buttonHtml);
?>
</form>
Now the submit tag is within the form tag (and will behave as as intended), it is simply a case of using CSS to style these and any other elements to give you the presentation that you desired (might need to remove padding, margin etc. from form element).
.submitLink {
font: inherit;
background-color: transparent;
text-decoration: underline;
border: none;
color: blue;
cursor: pointer;
}
.submitLink:focus {
outline: none;
}
form{
padding: 0;
margin: 0;
}
The big upside is that now you do not need any un-necessary javascript, giving maximum accessibility and maintaining the functionality that users expect.
Also feels less complicated to me and that it is less likely to need updating.
Side note: if your form allows users to delete multiple bookmarks at once (seems like it should) you might want the text on the button to read; delete bookmark(s) Hope you had considered that ;)
You can use jQuery AJAX for this.
Because, calling PHP script with form submit will cause total page refresh.
you need to just delete the selected checkbox row and delete the entry from database.
I will explain the pseudo logic for it.
On click of the link Delete BM, call javascript for AJAX.
First open a confirm dialog.
Through AJAX, pass the id to be deleted to backend PHP file.
In PHP file, write the code to delete the record.
If record gets deleted, echo success there else failure.
If in AJAX, we get results success, delete the respective rows.
jQuery $.ajax()
I am converting an old double dropdown box search form. With the old method, the form was submitted on each user selection using this:
<form name="navTwo">
<select name="item" id="item" onChange="document.location.href=document.navTwo.game.options[document.navTwo.game.selectedIndex].value">
The problem with the old method is that users were forced to look thru the second dropdown that contained an ever growing number of options.
I opted to make a new search using one auto submit drop down and a new jquery type ahead search field (thanks to Jamie McConnell, jamie#blue44.com). Everything works great with the type ahead. However, I cannot figure out how to submit the new form once the user picks the type ahead item. Ideally I would like to force the user to click submit once they've selected that second item.
I've tried carrying the id of the second search item and placing it in a hidden input but I cannot get the variable set to the id. Here is what I've tried so far, unsuccessfully;
//The page name is dash3.php
//If list = 1 it will add the record
//The jquery stuff works fine, it adds the value to the input field, I need it to grab the id of that record, not just the title. The $vid is empty, not sure how to set it.
//The code below is missing the submit button, I tried adding a link so that I could see the variables.
<form name="nav">
<div>
Start typing the name of the item, select the correct title when it appears:<br />
<input type="text" size="30" value="" id="inputString" onkeyup="lookup(this.value);" onblur="fill();" />
<input type="hidden" value="?list=1&ptfm_ctrl=1&vid=<?=$vid?>" />
</div>
<div class="suggestionsBox" id="suggestions" style="display: none;">
<img src="upArrow.png" style="position: relative; top: -12px; left: 30px;" alt="upArrow" />
<div class="suggestionList" id="autoSuggestionsList">
</div>
</div>
<strong>+</strong>
</form>
So, to make my question more clear;
How can I grab the id of the type ahead record that is being placed in the input field by a jquery autocomplete script and make a self referencing form carrying this id to the same page?
Thanks much!
Maybe this example in the autocomplete documentation will help: http://jqueryui.com/demos/autocomplete/#custom-data
The idea is that you populate your autocomplete boxes with enough data for the user to select the right choice and then provide the id and hook into the success event.
select: function( event, ui ) { ... }
This might help get you started: http://jsfiddle.net/shanabus/HGF59/
Instead of the alert that fires upon the second dropdown selection, do something like update your form action:
$("#myForm").attr("action", $("#myForm").attr("action") + "/" + ui.item.id);
and then submit if needed. Hope this helps!
I am playing with the Ajax Live Search functionality from the W3Schools website. It is working fine except I would like the results div, #livesearch, to hide again when the user clicks away from it. I have found an example piece of code which does this but I cannot comdine the two successfully. If I add the code the search results can be hidden when the user clicks away but the user has to click first to see them, which obviously wont work.
http://www.w3schools.com/php/php_ajax_livesearch.asp
http://bytes.com/topic/javascript/answers/676788-hide-div-tag-if-outside-div-clicked
Can anyone point me in the right direction?
Thanks
Chris
Checkout the javascript 'onblur' event.
You could create a new function which cleared the div:
blurFunction() {
document.getElementById("livesearch").innerHTML = ''
}
The onblur event:
<input type="text" size="30" onkeyup="showResult(this.value)" onblur="blurFunction()" />
EDIT: Actually I just noticed the showResult function already caters for clearing the div, so just insert:
<input type="text" size="30" onkeyup="showResult(this.value)" onblur="showResult('')" />
If I'm reading this right, you want the dropdown to disappear when the input loses focus and reappear when the mouse is moved over it, not just clicked?
I was able to achieve this by using an onblur event to hide the box (your example that you found works equally well, I believe). onblur="hide(this)" to hide the dropdown div. Hide js function is the same: function hide(id)
{
document.getElementById("livesearch").style.display = "none";
}
To make it reappear on mouseover, I added an onmousemove event to the input: <input type="text" size="30" onkeyup="showResult(this.value)" onblur="hide(this)" onmousemove="showResult(this.value)" />
.
Most importantly I added this line document.getElementById("livesearch").style.display = "block"; in the xmlhttp.onreadystatechange=function() to make the div reappear.
I need to make this show an error if the user tries to leave the page without checking this tickbox. It has no other use other than visual, is there a way to implement such a thing?
<span>
<input value="1" type="checkbox" name="salgsvilkar" ID="checkbox2" style="float:left;"
onclick="document.getElementById('scrollwrap').style.cssText='
border-color:#85c222;
background-color:#E5F7C7;';" />
<label for="checkbox2" class="akslabel">
Salgs og leveringsvilkår er lest og akseptert
</label>
</span>
Attached CSS is just for styling, no point posting it up.
I have tried:
{literal}
<script type="text/javascript">
if ($("#checkbox2").val()==1){
alert('Please accept the terms of sale');
//or you can use other method of showing the error. lightbox? showing error msg on a span, etc.
}
</script>
{/literal}
Entered this in the markup just before the checkbox, but it doesn't want to work.
UPDATE:
Further to answers given, here is the form submit code..
{form action="controller=checkout action=payOffline query=id=$method" handle=$offlineForms[$method] method="POST"}
{include file="block/eav/fields.tpl" fieldList=$offlineVars[$method].specFieldList}
<div id="handel_fortsett_btns">
<p class="submit">
<span><span><span><span> </span></span></span></span>
<input type="hidden" name="step" value="{$step}" />
<label></label>
<button type="submit" class="submit" name="{$method}" id="fullfor_btn" title="Fullfør bestillingen nå" value=""> </button>
</p>
</div>
{/form}
Thanks.
Yes. use jquery.
$(document).ready(function() {
//this should capture your submit button click event and the return false will stop the submission.
$("#fullfor_btn").click(function(){
if ($("#checkbox2").val()==1){
alert('your error msg');
//or you can use other method of showing the error. lightbox? showing error msg on a span, etc.
return false; //or use other method to stop your form from submitting.
}
});
)};
and here's a bit of tutorial to get you started, don't fret it if you don't know what to use at first. just learn the selector and slowly work your way up. it will be a worthwhile investment :)
and how are you submitting the form now?
if it's just a submit button you can use jquery to add the click event to the submit button and return false when you don't want the button to submit.
["Salgs og leveringsvilkår er lest og akseptert" (Swedish? Norwegian?) is about accepting terms and conditions.]
I hope it is not just for display. You need to check server-side too that the user has accepted your terms.
To do client-side form checking, you will want to use JS to override the submit button's action, check the data (as melaos demonstrates, though jQuery is not needed), and display the comments next to each form element. A bit of a pain really. You have to re-validate it all server-side too in case JS is accidentally (or not) disabled.