Okay the title might be confusing, as i myself still confused as how to phrase it.
Hi, i am a beginner in PHP, and definitely no experience in js or other languages.
I'm trying to make an input type (datalist), where when the user press enter, or select the options from the list, de input would passed into an array, then displayed as static text next to the original input field, while the original input field would be emptied, allowing user to type/select another option, and when the user chose other option/press enter, the new value would be added to the array. And then when the user click the submit button, the whole array of that field would be then passed as POST.
Well if my explanation still confusing, just imagine those sites where you can submit an articels, and we can type/chose the 'tags' for the articles.
I heard tou have to implement js on this one, can anyone please help explain it to me? I would really appreciate it
Thankyou
A way of doing that would be to setup a form with the input paired with a button plus divs for appending the user's input and then going through the logic below
the user inserts a value into the input and clicks a button
The button click activates a jquery event where the function obtains the user input
It then checks if the value is empty and then appends the value in a <p> tag to the display div and an input of type hidden to the hidden div with the name attribute as name[].
Later when you submit the form you can obtain the values using the names[] variable which will store them as an array. You can edit this to anyway you want.
For the html
<input id="name" name="name" type="text"/>
<font size="1">Add Name</font>
<div id="display"></div>
<div id="hidden"></div>
And then for the javascript
// Add name
$("#add_name").click(function (e) {
//prevent submit of form
e.preventDefault();
var name = $('#name').val();
//check if input is empty
if(name){
$("#display").append("<p>" + name + "</p>");
$("#hidden").append("<input type='hidden' name='names[]' value='" + name + "'>");
} else {
alert("Please insert name before submitting")
}
$('#name').val("");
});
Let me know if it helps or if i can help you further
Related
I have this problem, a textbox is assigned to get the value of the datepicker. I have no problems doing it initially (meaning at first with no changes on the datepicker) since there's a button to be clicked to produce the hidden textbox. But the problem arises when the value of the datepicker is changed (after the textbox is generated). Here's the sample:
Datepicker:
<input type='text' name='devd' id="devd_1" class='pickdate' size='10' />
Hidden Textbox:
<input type='hidden' name='devd_box' id='devd_box_1'/>
The button that I mentioned should only be used once. So my problem now is how to populate the hidden textbox if the value of the datepicker has changed.
You may notice the last number of the ID, that is their common reference so that it can update the right box since it has multiple datepickers/boxes.
Thanks for all the help!
P.S: The last number after the IDs are dynamically populated thus I can't just hardcode the ID of the datepicker.
Actual solution for those who need it:
$('.pickdate').on('change', function (ev) {
var string_id = this.id;
var lastnum = string_id[string_id.length -1];
$('#devd_box_' + lastnum).val(this.value);
});
Simply look for the onChange event.
$('#devd_1').on('change', function (ev) {
$('#devd_box_1').val('Your text here');
});
This will change the text on the hidden field whenever there's a change made on the datepicker field.
Regarding the dynamic id part -
Make a javascript function for it and call it to get the actual id.
Note:
Please refer the question for the actual solution.
I am creating a calculator in PHP and I should have this kind of structure of my HTML, where my numbers are clickable buttons, and the number that has been first clicked will be the first value and the second number I click will be the second value. I have no idea on how its gonna work, is it possible? if so how here's my code
<html>
<head>
<title>Calculator</title>
</head>
<body>
<div id = "structure">
<?php
if(isset($_GET)){
$value += $_GET;
}
?>
<form method = "GET " action = "calculator.php">
<input type = "submit" name = "one" value = 1>
<input type = "submit" name = "two" value = 2>
<input type = "submit" name = "three" value = 3>
<input type = "submit" name = "operand" value = "+">
</br>
<input type = "submit" name = "four" value = 4>
<input type = "submit" name = "five" value = 5>
<input type = "submit" name = "six" value = 6>
<input type = "submit" name = "operand" value = "-">
</br>
</form>
</div>
</body>
</html>
I haven't put all the numbers in the calculator for posting purposes
As others mentioned, the best way to do this is to use Client-side coding (Javascript). However, if you have to write a PHP code, then you need to submit the form twice. The first time, put the input variable (first number) in a hidden input element of the form and have print the html again this time with the extra hidden input element. The second time, look for that hidden input value: if it exists then it means that the new input is the second number and the hidden input is the first number. Get the value of the hidden input, get the new number, add them together and display the results. Make sure you reset the hidden input value.
Since this is a book exercise and the point is for you to write the code, I'm not going to give you any code. But, I can point you in the right direction (or at least one of them).
Consider using some kind of value that can be sent with each request that stores the current accumulated value of all operations. This probably should be displayed somewhere and also placed in a field that PHP will be able to read on form submit (Hint: have you ever heard of the hidden input type?). How will you keep track of the last operation? Maybe you could use another one of these fields to store the operation until another button is pushed.
What code can you use to check if the form is submitted? How can you check which button is pushed. Which values will be set if + is pushed? How about if a number is pushed? What if multiple numbers are pushed in a row?
More things to consider: Try playing with a real calculator. When are results displayed? What order of operations is used? Every operation has a left hand side and a right hand side. What happens when you push multiple numbers in a row. What about decimals? Should there be a clear button?
You'll need a way to keep track of previous inputs. Every time you click a button, a request gets sent to the server with that info (in $_GET) but the old inputs are no longer available. A few methods:
Hidden form elements
Each time the user clicks, you read the value and output it back into the page in a hidden form element. Each time you have to read the value of the hidden element using your existing method with $_GET, figure out what you need to do mathematically, and save the old stuff and new stuff into the hidden element again for the next input.
See this page for an example.
Cookies
You can use setcookie to set a cookie with the value the user entered. Each time the user clicks a button, you want to load the value from the cookie and append the current input. When the user clicks the = button, you load the cookie data and parse the expression. You make it easier and store the parts of the expression in some kind of delimited string in the cookie so you have operand,operator,operand and then you can easily compute the result. Hitting a clear button would clear the value of the cookie.
This tizag tutorial is a pretty good example of what you want to do with cookies.
Javascript
Obviously the easiest way. Since the state will be maintained, you don't need to pass values back and forth.
This is a bit complex so I hope I word this right.
I have a form that loads a list of options and starts with one static input:
<span id="keyword_list_out" class="input"><input class="keys margin-bottom" type="text" name="keywords[]" />
When the page is loaded an Ajax call displays additional input fields that belong to the list such as:
<span class="field-wrapper"><input class="keys" type="text" name="keywords[]" value="Option One" /><a class="remove-keyword" href="javascript:void(0);"><img src="images/icons/cross-button-icon.png" /></a></span>
<span class="field-wrapper"><input class="keys" type="text" name="keywords[]" value="Option Two" /><a class="remove-keyword" href="javascript:void(0);"><img src="images/icons/cross-button-icon.png" /></a></span>
These options are prepended to the top of the first static input field ID: keyword_list_out.
The user can dynamically add more input fields and they can remove existing fields.
All of this so far works fine. My problem is accessing the data contained within the input fields. I need to be able to perform three functions once the form is submitted:
If the user has removed an option I need to remove this from the database
If the user has added a field I need to insert this into the database
If the user changes the value of an existing field I need to update this in the database
I can access the data within the input fields by using the input name 'keyword_name[]' as an array, and then I can loop through the array.
However this does not address existing options that have a specific ID number. I can assign ID numbers to the fields that were loaded from the Ajax call, however the static field and user added fields wont have ID numbers, as these arent necessary. These fields will simply be inserted into the database.
So I guess my question is how would I go about determining which existing option belongs to what ID number in the database. I should add that the options are not uniquely named.
I considered something such as:
Provide ID numbers only for the Ajax loaded fields
Upon submit loop through each input and prepend the ID to the end of the name value using a delimiter the user wont provide. IE: Option Two---1
With PHP looping through the array and exploding the array value where it matches '---'
If a match was found on '---' update the database, else insert into the database
Any thoughts?
UPDATE
I have divided the input fields into two arrays: existing_options[] and new_options[].
In my Jquery script prior to posting i have added:
var existing_options = $('input[name=existing_options]').attr('value');
var new_options = $('input[name=new_options]').attr('value');
The Ajax data being sent is:
'existing_options[]=' + existing_options + '&new_options[]=' + new_options;
However PHP is returning that these values are strings and not arrays. Missing something here....
I would suggest on using an auto increment id on the database side. When you load the page, have the id placed like so <span class="field-wrapper" id="$row[id]"> and than when deleting use:
$('.remove-keyword').on('click', function(){
var id = $(this).parents('span').attr('id');
place ajax post here with data sent being this id.
});
And basically it'll be the same for adding a keyword, except use ajax to post to your script, and use mysql_insert_id(); in your script as a returning id than dynamically create the next row.
When the fields are loaded via AJAX assign them IDs
<input class="keys" type="text" id="keyword_11" name="keywords[]" value="Option Two" />
<input class="keys" type="text" id="keyword_12" name="keywords[]" value="Option Two" />
On submit clicked then in jQUery you can loop through the keywords
var new_keywords=Array();
var existing_keywords=Array();
$("input[name^='keywords']").each(function(){
var id = $(this).attr("id");
var val=$(this).val();
if(id=="" && val!="")
{
new_keywords.push($(this).val());
}
else if(id!="")
{
var keyword_id=id.split("_")[1];
existing_keywords.push({"id":keyword_id,"val":val});
}
});
// call AjAX function add new_keywords to database
// call Ajax function to update existing keywords
UPDATE 1
In the success function of adding new_keywords to database do update the existing dom via AJAX so that if you add new keyword, then you edit it and try to save it will have the ID associated with it.
Just want to know if there is a way to detect how many times a user has clicked a button by using Jquery.
My main application has a button that can add input fields depend on the users. He/She can adds as many input fields as they need. When they submit the form, The add page will add the data to my database. My current idea is to create a hidden input field and set the value to zero. Every time a user clicks the button, jquery would update the attribute of the hidden input field value. Then the "add page" can detect the loop time. See the example below.
I just want to know if there are better practices to do this. Thanks for the helps.
main page
<form method='post' action='add.php'>
//omit
<input type="hidden" id="add" name="add" value="0"/>
<input type="button" id="addMatch" value="Add a match"/>
//omit
</form>
jquery
$(document).ready(function(){
var a =0;
$("#addMatch").live('click', function(){
//the input field will append //as many as the user wants.
$('#table').append("<input name='match"+a+"Name' />");
a++;
$('#add').attr('value', 'a'); //pass the a value to hidden input field
return false;
});
});
Add Page
$a=$_POST['a']; //
for($k=0;$k<$a;$k++){
//get all matchName input field
$matchName=$_POST['match'.$k.'Name'];
//insert the match
$updateQuery=mysql_query("INSERT INTO game (team)
values('$matchName')",$connection);
if(!$updateQuery){
DIE('mysql Error:'+mysql_error());
}
}
I'm a bit confused. After this:
$('#add').attr('name', 'a'); //pass the a value to hidden input field
shouldn't you actually store the value of a?
$('#add').attr('name', 'a').val(a);
$('#add').attr('name', 'a').val(a); ????
That's not correct, you should use:
$('#add').attr('value', a);
send the content of the "a" variable to the "value" property of element with ID "add"
I do believe that's what you want to do....
I have several forms inside DIVS on my page.
I have one form which contains a text field and is always visible, and this is where the user hits 'enter' key and submits...
I want to get values selected in the other forms on the page, and submit them all together, not one by one, so that my PHP code can use "ALL VALUES" and search a mysql database...
Is this possible by javascript using the "<form onsubmit>" to call a javascript?
any codes would be appreciated...
thanks
Without some Javascript hocus-pocus, you can't. One form = one request.
You can do it with JS, and you have a few options. The easiest would be to loop through all the forms on the page, and basically duplicate all the input fields and values into one form and then submit that combined form.
With jQuery it'd go something like this:
$("form").submit(function() {
combineAndSendForms();
return false; // prevent default action
});
function combineAndSendForms() {
var $newForm = $("<form></form>") // our new form.
.attr({method : "POST", action : ""}) // customise as required
;
$(":input:not(:submit, :button)").each(function() { // grab all the useful inputs
$newForm.append($("<input type=\"hidden\" />") // create a new hidden field
.attr('name', this.name) // with the same name (watch out for duplicates!)
.val($(this).val()) // and the same value
);
});
$newForm
.appendTo(document.body) // not sure if this is needed?
.submit() // submit the form
;
}
You need to make a script which will collect the data from the forms, and inject them into the only form that is visible. Only one form will be submitted, you can not submit multiple forms.
You can create multiple hidden fields, or you can construct a single hidden field in that form, then use javascript to collect all the data from the various forms, then create a JSON string, set the value of the hidden one, and submit.
Edit:
Say you have a single hidden input like this:
<input type='hidden' name='hiddenfield' id='hiddenfield' />
you could use JQuery to do this:
$('#hiddenfield').val('myvalue');
To get the value from other forms is as simple as calling $('#elementid').val()
before form submission. To use JQuery, go to the jquery website, download the library, and link it (follow their installation guide).
you can add an onsubmit to that form, and then collect other values with javascript:
<input type="hidden" name="hidden1" id="hidden1" />
<input type="hidden" name="hidden2" id="hidden2" />
<script>
document.getElementById("the_form").onsubmit = function(){
document.getElementById("hidden1").value = document.getElementById("other-field1").value;
document.getElementById("hidden2").value = document.getElementById("other-field2").value;
};
</script>
Wrap the whole Page in your form tag (if possible) and use the server side code, along w/ Javascript, to handle your business rule validation.
kind of a hack solution, but it should minimize the necessity for Javascript "hacks" depending on your skill level with javascript.