I have a jquery function that retrieves information that a user clicks on in a database table.The user can select any one of ten rows that becomes highlighted when mouseover and when the user clicks the highlighted row the function retrieves it and puts it into a textbox. Then if the user submits this request for purchase I want to echo the textbox on the next page which is an order form.
The code below works well up until I try to retrieve the information from the url. I can see that it is passed in the url to the next page but after trying for two days I have not been able to retrieve it. I don't know where to go from here. Can someone look at this and see if I have not coded properly or done something wrong.
I have copied down the code that applies...
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("table tr").click(function(){
$("#txttread").val($.map($(this).children('td:not(:eq(7))'), function (item) { return $(item).text() }).join(' - '));
});
});
$(document).ready(function() {
$('.pickme tr').not(':first').hover(
function() { $(this).addClass('highlight'); },
function() { $(this).removeClass('highlight'); }
).click( function() {
$('.selected').removeClass('selected');
$(this).addClass('selected').find('input').attr('checked','checked');
});
});
</script>
</head>
<body>
<form action="Order.html" method="GET" name="myform2" />
<div>
<div style="text-align:left height:250px;">
<DIV STYLE="font-family: Arial Black;
color: black; font-size: 20pt;">
Select from inventory below:<br/><input type="text" style="width:500px; height:35px;" rows="1" STYLE="font-family: Arial Black;
color: red; font-size: 20pt;" name="txttread" id="txttread" DISABLED /></div></div></div>
<div>
<div style="text-align:center;">
<br/><input type="button" button id="getone" name="getone" value="Submit your request for purchase" onclick="window.location.href = 'http://localhost/order.html?txttread='+ ( $('#txttread').val() )"><br/><hr/>
</body>
</html>
The url on the next page is....
http://localhost/order.html?txttread=Firestone - All Season - FR-710 - 225/60/16 - 4 - 3 - 60.00
I think this has to do with the URL not being encoded correctly. On that last line where you append the $('#txttread').val(), you should wrap it with encodeURIComponent():
<input type="button"
button id="getone"
name="getone"
value="Submit your request for purchase"
onclick="window.location.href = 'http://localhost/order.html?txttread=' + encodeURIComponent($('#txttread').val());">
This might not answer your question completely, but consider this:
window.location.href = 'http://localhost/order.html?txttread='+ ( $('#txttread').val() )
You should apply proper escaping when you pass parameters:
window.location.href = 'http://localhost/order.html?txttread=' + encodeURIComponent( $('#txttread').val() );
To access the value of txttread from an HTML page:
function getParameterByName(name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
As found here: https://stackoverflow.com/a/901144/1338292
Related
I am developing the app using CakePHP 1.3 Now I want to make the "Insert function" to add new user into database. I have 2 fields user & pass to insert. But I not only insert 1 user, I want insert one or multiple user (optional). If I want to add more user I will click to "add more" to add new field in view.
In cakephp, it required when we want to insert a array with multiple data. The field name will be define as:
<?php
echo $this->Form->input('Modelname.0.fieldname');
echo $this->Form->input('Modelname.1.fieldname');
?>
and in view will be:
<input type="text" id="Modelname0Fieldname" name="**data[Modelname][0][fieldname]**">
<input type="text" id="Modelname1Fieldname" name="**data[Modelname][1][fieldname]**">
My question is: Does JQuery have some function to add new element and how can I increase the index number follow the pattern above data[Modelname][0][fieldname]
Thank for your view and suggestion.
I've created this code, here it is, I've tested it and it works
http://codepen.io/anon/pen/xbxVQG
var $insertBefore = $('#insertBefore');
var $i = 0;
$('#plusButton').click(function(){
$i = $i+1;
$('<br><div class="Index">User N. ' + $i + '</div><br>Username:<br><input type="text" id="Modelname' + $i + 'Fieldname" name="**data[Modelname][' + $i + '][fieldname]**"><br>Password:<br><input type="text" id="Modelname' + $i + 'Password" name="**data[Modelname][' + $i + '][Password]**"><br>').insertBefore($insertBefore);
});
#Userlist{
border-style:solid;
width: 300px;
margin: 0 auto;
text-align:center;
padding: 0.5em;
}
.Index{
background-color:grey;
text-align:left;
}
#plusButton {
background-color:green;
color: white;
font-size:1.9em;
width: 300px;
margin: 0 auto;
text-align:center;
cursor: pointer;
}
<html>
<head>
<title>Add New Users</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<form action="your-script.php" method="post" id="Userlist">
<div class="Index">User N. 0</div>
Username:<br>
<input type="text" id="Modelname0Fieldname" name="**data[Modelname][0][fieldname]**"">
<br>Password:<br>
<input type="text" id="Modelname0Password" name="**data[Modelname][0][Password]**">
<br>
<div id="insertBefore"></div>
<br><br><input type="submit" value="Add User">
</form>
<div id="plusButton">+</div>
</body>
</html>
some important notes:
1- The div who's id="insertBefore" is just to tell jQuery where to put the new duplicated fields.
2- The jQuery code works with an index variable ($i) that starts in 0 and gets incremented by 1 on each new click on the "+" button (so the first time you click, it should get to 1)
3- The original Form's code (where value is 0 by default) is printed everytime the + button is clicked, but replacing each 0 in the html code by '+$i+'
3.2 - If you make some changes to the code of your form, by this method, you should change the javascript code as well. I know it's not an elegant solution to do this, but it shouldn't be so difficult either, just remember to copy the exact html code, delete all intro's and replace all 0's with '+$i+'
4- The "Index N." div is just keeping track of the user's number, you could put your own text there, like "User NÂș 0" and in the jQuery code replace the 0 with the value of $i
5- You could put a limit to the number of users (example:10) that can be added by creating an if($i<10){} variable inside the .click() function
Just write a jQuery code to append a user field. and also send data-id to the javascript.
Let say for example. in your form.
<div id="segment">
$this->Form->input('User.1.name',array('class'=>'user','data-id'=>1));
</div>
in jquery.you can have a function like this on click of add user,
var lastid = parseInt($('.user:last').attr('data-id');
var newid = lastid+1;
var input = "<input name='data[User][" + newid + "][name]' class='user' id='user-" + newid + "' data-id='" + newid + "' type='text'><br/>";
$('#segement').append(input);
Note that double check the input string, I might miss a quote or
anything.
Thanks for all answers about this, I was not test your code but I found the way to append and increase the index number too. When I have time, I will research about your code.
My code is follow this thread http://www.sanwebe.com/2013/03/addremove-input-fields-dynamically-with-jquery. He made it easily to understand.
The JS:
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div><input type="text" name="mytext[]"/>Remove</div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
and the HTML:
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div><input type="text" name="mytext[]"></div>
</div>
The demo you can see in that link above.
More thank for everybody again.
I am having trouble with this code. I don't understand how to add another box apart from the one that it already adds with ajax within the code when I press the link Add more. I want to be able to add two text boxes when I press the add more link, one for hobby and another one for age but I only get one. What I tried was on the on click function I tried to add another var html_box2 but it did not work out.
<!DOCTYPE html>
<html>
<head>
<title>Add or Remove text boxes with jQuery</title>
<script type="text/javascript" src="//code.jquery.com/jquery-latest.js"></script>
<style type="text/css">
<!--
#main {
max-width: 800px;
margin: 0 auto;
}
-->
</style>
</head>
<body>
<div id="main">
<h1>Add or Remove text boxes with jQuery</h1>
<div class="my-form">
<form role="form" method="post">
<p class="text-box">
<label for="box1">Box <span class="box-number">1</span></label>
<input type="text" name="boxes[]" value="" id="box1" />
<a class="add-box" href="#">Add More</a>
</p>
<p><input type="submit" value="Submit" /></p>
</form>
</div>
</div>
<script type="text/javascript">
jQuery(document).ready(function($){
$('.my-form .add-box').click(function(){
var n = $('.text-box').length + 1;
if( 5 < n ) {
alert('Stop it!');
return false;
}
var box_html = $('<p class="text-box"><label for="box' + n + '">Box <span class="box-number">' + n + '</span></label> <input type="text" name="boxes[]" value="" id="box' + n + '" /> Remove</p>');
box_html.hide();
$('.my-form p.text-box:last').after(box_html);
box_html.fadeIn('slow');
return false;
});
$('.my-form').on('click', '.remove-box', function(){
$(this).parent().css( 'background-color', '#FF6C6C' );
$(this).parent().fadeOut("slow", function() {
$(this).remove();
$('.box-number').each(function(index){
$(this).text( index + 1 );
});
});
return false;
});
});
</script>
</body>
</html>
These lines of code add one box
var box_html = $('<p class="text-box">whatever goes here</p>');
box_html.hide();
$('.my-form p.text-box:last').after(box_html);
box_html.fadeIn('slow');
You can copy and modify them to create another box like
var box_html = $('<p class="text-box">whatever goes here</p>');
box_html.hide();
$('.my-form p.text-box:last').after(box_html);
box_html.fadeIn('slow');
var box_html2 = $('<p class="text-box">whatever has to go here</p>');
box_html2.hide();
$('.my-form p.text-box:last').after(box_html2);
box_html2.fadeIn('slow');
I'm very new to PHP, so bear with my ignorance. I've got the following script that searches an excel sheet for cell data (it's a really basic company phonebook):
<html>
<?php echo "Search:" ?>
<form id="form1" method="post" action ="<?php echo $_SERVER['PHP_SELF']; ?>"> <label>
<input id="search" name="search" type="text" />
</label>
<label>
<input type="submit" />
</label>
<img src="loading.gif" width="16" height="11" />
</form>
<input type="reset" value="Reset">
<?php
$search= $_REQUEST['search'];
if ($search > ''){ $search = $search;} else { $search = '';}
?>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['table']});
</script>
<script type="text/javascript">
var visualization;
function drawVisualization() {
var query = new google.visualization.Query(
'https://docs.google.com/spreadsheet/pub?key=0Ap2dozrbYI5vdEV5ZmtzU3hCdktzWDU0NTdOQjRSNkE&single=true&gid=0&output=html');
query.setQuery('SELECT A, B, C, D where upper(A) like upper("%<?php echo $search; ?>%") or upper(B) like upper("%<?php echo $search; ?>%") order by A asc label A "Company", B "Contact Name", C "Contact Number", D "Company General Contact"');
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
visualization = new google.visualization.Table(document.getElementById('table'));
visualization.draw(data, {legend: 'bottom'});
}
google.setOnLoadCallback(drawVisualization);
</script>
<div id="table"></div>
</div>
</html>
When no text is entered and the user clicks submit, the view resets to show the complete excel sheet. I'd like to add a reset button that functions the same way (it makes more sense to the user to have an actual "reset" button.
Edit: Just a note that I'm not trying to simply clear the search input. Essentially, I'd like to replicate what the submit button does when a blank search is performed (which is display all the data).
Add this line to your html form:
<input type="reset" value="Reset">
There are a number of issues here that need to be addressed. I've cleaned out some of the code you posted but I didn't want to totally rewrite everything you did. It looks like you might have copied and pasted a couple examples you found on the web into one project. It really helps if you review what a script does before you put it into production. Doing so will help you with some of these issues. For instance, in one line you check a variable to see if it is greater than empty string. You then assign it to itself if it is and you assign it to empty string if it is empty. Basically, that line does nothing. Read through your code so you know what it does.
In the end, I figured out that you didn't really need PHP for anything. You are simply using it to post back to the server and reload the page. Since you are using JavaScript to actually load your information, I decided to do everything in JavaScript. It makes the page simpler and it prevents unnecessary postbacks. I also formatted your code a bit and cleaned it up some. However, this still needs to be further refined and cleaned up. I just got it to a working state:
<html>
<body>
<input id="search" name="search" type="text" />
<button id="submitQuery">Submit Query</button>
<button id="resetQuery">Reset Query</button>
<div id="table"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', { packages: ['table'] });
var visualization;
var searchTerm = '';
function drawVisualization() {
var query = new google.visualization.Query(
'https://docs.google.com/spreadsheet/pub?key=0Ap2dozrbYI5vdEV5ZmtzU3hCdktzWDU0NTdOQjRSNkE&single=true&gid=0&output=html');
query.setQuery('SELECT A, B, C, D where upper(A) like upper("%' + searchTerm + '%") or upper(B) like upper("%' + searchTerm + '%") order by A asc label A "Company", B "Contact Name", C "Contact Number", D "Company General Contact"');
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
visualization = new google.visualization.Table(document.getElementById('table'));
visualization.draw(data, { legend: 'bottom' });
}
google.setOnLoadCallback(drawVisualization);
$(function () {
$('#submitQuery').click(function (e) {
searchTerm = $('#search').val();
drawVisualization();
return false;
});
$('#resetQuery').click(function (e) {
$('#search').val('');
searchTerm = '';
drawVisualization();
return false;
});
});
</script>
</body>
</html>
Instead of using buttons in a form to do a postback, I made the buttons fill in the variable appropriately and call the function to draw the visualization. I did draw in jQuery to make things a bit easier (note the call to the CDN for it). That made the code cleaner and easier to use. You don't have to do it that way but you will need to rework my code if you take it out.
Let me know if you have any questions. As it stands now, this code should do exactly what you want it to do.
So i have been getting help from another question on here but i need some help getting this code to work
What i am trying to do is have the form send the "count" var to JS so that it can do a for loop a user specified amount of times and also have it send the other 2 variables to php for it to process the form data.
But I am new to javascript so i dont know how i could accomplish this.
here is the code for the html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<style type="text/css">
body {
font-family: Arial, Helvetica, sans-serif;
font-size: 12px;
font-style: normal;
line-height: normal;
color: #FF0000;
background-color: #000000;
}
.style7 {color: #FF0000}
</style>
<script type="text/javascript" src="jquery-1.5.1.min.js"></script>
<script type="text/javascript">
$(function(){
$("#Submit").click(function(){
var count = form.count.value;
var number = 0
for (i=1;i<=#count;i++)
{
$.ajax({
url:"process.php",
type:"get",
data:$("form").serialize(),
success:function(response){
number++
var obj = jQuery.parseJSON( response );
var success = obj.success;
var actionsNumber = obj.number;
$("#result").html('<b>'+number+'</b>');
}
})
}
})
})
</script>
</head>
<body>
<form action="" method="post">
<center> <p>
<label><b><big><big><big><big><big><big><big>Page</big></big></big></big> </big> </big></big></b></label>
</p>
<p>
<p>
<label><strong>MN</label>
</p>
<input name="MN" type="text" value=""/>
</p>
<p>
<p>
<label><strong>Number to Send</label>
</p>
<input name="count" type="text" value = "1"/>
<input name = "number" type = "hidden" value = "$number"/>
</p>
<p>
<p>
<label><strong>Provider</label>
</p>
<select name="provider">
<option value="">Choose One...</option>
</select>
</p>
<p>
<input id="Submit" type = "button" value = "Send">
</p>
<p>You have done <span id="result">0</span> actions</p>
</center>
</body></html>
and this is process.php
<?php session_start();
// process your form data as you do
//:::::::::
//
if(!isset($_SESSION['number'])){
$_SESSION['number'] = 0;
}
$number = $_SESSION['number']++;
sleep(.5);
// output json response
echo'{"success":"true","number":"'.$number.'"}';
?>
so I need for (i=1;i<=#count;i++) to work with the number the user puts in the "count" field and I also need process.php to get the stuff from the other boxes.
any help?
You can read out the number with $('#count').val(). Your codes looks a bit weird though. What are you trying to accomplish?
Well, first you need to bind your click event to the correct element in the DOM. Your existing code looks like this...
$("#Submit").click(...);
#Submit refers to an element with id="Submit" -- which there isn't one on your page. What you should be doing is something more like this...
$('form').bind( 'submit', function( ){ ... } );
Now your form submission event is being properly captured, you just need to get the values out.
$('form').bind( 'submit', function( )
{
var self = $(this); // -- reference to form element
var count = self.find( 'input[name="count"]' );
console.debug( count.val( )); // -- if you don't have a console, get one... or just use alert()
} );
I have working script that the user completes inputs on a form and when they submit the form and the content of the form inputs are entered as a table row.
Is there any way of, I think within the JS to make each row have a unique ID and add a delete button to the last colum of each row so the user can delete an individual row.
Thanks for saving a life!!!!
HTML Form
<form id="my_form" action="table_form.php" method="post">
<div style="width:10%; float:left;">
Quantity<br />
<input name="field_1" type="text" id="field_1" size="3" />
</div>
<div style="width:20%; float:left;">
Part Number<br />
<input type="text" id="field_2" name="field_2" />
</div>
<div style="width:30%; float:left;">
Notes<br />
<input name="field_3" type="text" id="field_3" size="45" />
</div>
<div style="width:20%; float:left;">
Unit Price<br />
<input type="text" id="field_4" name="field_4" />
</div>
<div style="width:20%; float:left;">
<br />
<input type="submit" value="Add Row" />
</div>
</form>
<!--
Here we create our HTML table.
Note the ID of the table. This will be used in our javascript file
Our table only contains a header row. All other content will be added dynamically
--><? $rowid = 1; ?>
<table width="100%" id="my_table">
<tbody id="my_table_body">
<tr>
<th width="5%"><div align="left">Qty</div></th>
<th width="19%"><div align="left">Part Number</div></th>
<th width="46%"><div align="left">Notes</div></th>
<th width="15%"><div align="left">Unit Price</div></th>
<th width="15%"><div align="left">Row Total</div></th>
</tr>
</tbody>
</table>
JS
window.addEvent('domready', function(){
$('my_form').addEvent('submit', function(e){
e.stop();
this.set('send', {
onComplete: function( response ){
var data = JSON.decode(response);
inject_row( $('my_table_body'), data );
}
});
var valid_form = true;
$$('#my_form input').each(function(item){
if( item.value == '' ) valid_form = false;
});
if( valid_form ) {
this.send();
} else {
alert('Fill in all fields');
}
});
var inject_row = function( table_body, data ){
var row_str = '<tr width="100%">';
data.each( function(item, index){
row_str += '<td>'+item+'</td>';
});
row_str += '<td><input type="submit" name="deleterow" id="deleterow" value="Delete" /></td></tr>';
var newRow = htmlToElements( row_str );
newRow.inject( table_body );
}
var htmlToElements = function(str){
return new Element('div', {html: '<table><tbody>' + str + '</tbody></table>'}).getElement('tr');
}
});
PHP
<?php
/**
* If nothing is being posted to this script redirect to
* our HTML page.
*/
if( ! $_POST ){
header('Location: newquote.php');
}
// create an empty array for our results
$results = array();
/**
* Stick the values from _POST into our results array
* while also stripping out any html tags
*
* This is where you would perform any required processing
* of the form data such as server side validation or updating
* a database.
*/
foreach( $_POST as $field ){
$results[] = strip_tags( $field );
}
// Echo our results as a JSON encoded string.
echo json_encode( $results );
?>
I agree with J-P, it sounds like you don't need an unique id here.
Since the question is tagged "jquery" I suggest using the live event binding, e.g.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready( function() {
$(".deleterow").live("click", function() {
$(this).parents("tr:first").remove();
});
});
function foo(id) {
$("#"+id).append('<tr><td>'+(new Date()).getSeconds()+'</td><td>x</td><button class="deleterow">delete</button></td></tr>');
}
</script>
</head>
<body>
<table id="t1">
<tr><td>a</td><td>A</td><td><button class="deleterow">delete</button></td></tr>
<tr><td>b</td><td>B</td><td><button class="deleterow">delete</button></td></tr>
<tr><td>c</td><td>C</td><td><button class="deleterow">delete</button></td></tr>
</table>
<button onclick="foo('t1')">add</button>
</body>
</html>
The function passed to $(document).ready() is invoked when ...well, as the name states, when the document (dom) is ready.
$(".deleterow").live("click", ... : Whenever a click event occurs on an element with the css class "deleterow" the function passed as second parameter is invoked. In this case
function() {
$(this).parents("tr:first").remove();
}
When the function is invoked the this-context is the element where the event occurred. parents("tr:first") returns the first/"nearest" tr element in the ancestor-axis of the current element. remove() is probably self-explaining...
edit: ok, now that the jquery tag is gone....
http://www.jaycarlson.net/blog/2009/04/06/live-events-in-mootools/ shows a live-event binding for mootools. Using that the "new" solution is quite similar to the jquery script
window.addEvent('domready', function() {
// add an onclick handler for all current and future button elements
// within the table id=t1
$('t1').addLiveEvent('click', 'button', function(e){
// a button in t1 has been clicked, this=button element
// get the "nearest" tr in the parent/ancestor-axis
// and remove it
$(this).getParent("tr").dispose();
});
});
This should be unique enough for this project:
var newDate = new Date;
var id = newDate.getTime();
Then it would just be a matter of adding it the row in your loop and linking it to your delete button.
I always use the php function uniqid(). It generates a unique id based on the time in microseconds. PHP Documentation.
You could loop through your results in PHP and add the result from uniqid() to each result before using json_encode().