Change the value of multiple dynamically PHP generated text-boxes using jquery - php

I have generated multiple text boxes using PHP with name="student[<?php echo $StudentID ; ?>]".
Now on a button click i want to change the value of all these text boxes using jquery.
How do i do this ? Please help.

You can use the Attribute Starts With selector, to look for student[ at the beginning of the name attribute:
$('input[name^="student["]').val('the new value');
It's probably unnecessary to include the [ at the end, and name^="student" will be sufficient, assuming you don't have other inputs with names like student_name or the like.
// If no conflicting named inputs, use
$('input[name^="student"]').val('the new value');

HTML
<input type="text" name="student[]"></input>
<input type="text" name="student[]"></input>
<input type="text" name="student[]"></input>
<button id="button">Change</button>
JavaScript
$('#button').click(function() {
$('input[name^="student"]').val('some value ');
});
JSFiddle

You can also simply add a class that is unique to all of those text boxes (i.e. changableTextBox) and then select it with that and change them all at once. It's also helpful for the future if you need to adjust some styling on all of them at once. Just declare that class in CSS and you're styling.
<input type="text" class="changeableStudentTextBox" id="student[11]" />
<input type="text" class="changeableStudentTextBox" id="student[23]" />
<input type="text" class="changeableStudentTextBox" id="student[45]" />
<input type="text" class="changeableStudentTextBox" id="student[66]" />
<script type="text/javascript">
$('#button').click( function() { $('.changeableStudentTextBox').val('hi!'); });
</script>

Related

JQuery: event.preventDefault() isn't preventing a refresh

I've been building a mail form that is supposed to pass the information into a php document that handles sanitization and mailing, but I didn't want it to refresh so i decided to use JQuery and AJAX. I'm fairly new to JQuery and haven't used any AJAX before so I am a bit of a rookie when it comes to this...
Even though I have the .submit(function(e){e.preventDefault();}); it still submits the ordinary way and gives an error when it can't find film_mail in the PHP. Which means that it isn't stopping the submit and isn't passing the code to the PHP.
I've tested with alerts and the JQuery works in to the if() but after that some thing goes wrong.
Here is the code that causes the issue (some of the classes and ids are in swedish but that shouldn't cause an error...)
HTML
<div id="film" class="hidden" >
<form id="film_form" action="formular-send.php" method="post">
<input id="film_mail" type="text" name="mail" placeholder="Mail adress">
<input id="film_nr" type="number" name="nr" min="1">
<input id="film_antal" type="number" name="antal" min="1">
<input id="film_namn" type="text" name="namn" placeholder="Namn">
<input id="film_adress" type="text" name="adress" placeholder="Adress">
<input id="film_ort" type="text" name="ort" placeholder="Ort">
<input id="film_postnr" type="text" name="postnr" placeholder="Postnummer">
<textarea id="film_medelande" name="medelande" placeholder="Medelande"></textarea>
<button id="film_submit" type="submit" name="submit">Skicka</button>
<div class="error-mesage" ></div>
</form>
</div>
JQuery
$(document).ready(() => {
var emne = $('#emneid').val();
if (emne == 'film') {
$('#film_form').submit(function(e) {
e.preventDefault();
var mail = $('#film_mail').val();
var nr = $('#film_nr').val();
var antal = $('#film_antal').val();
var namn = $('#film_namn').val();
var adress = $('#film_adress').val();
var ort = $('#film_ort').val();
var postnr = $('#film_postnr').val();
var medelande = $('#film_medelande').val();
var submit = $('#film_submit').val();
$.post('formular-send.php', {
film_mail: mail,
film_nr: nr,
film_antal: antal,
film_namn: namn,
film_adress: adress,
film_ort: ort,
film_postnr: postnr,
film_medelande: medelande,
film_submit: submit,
emne: emne
});
// I heard that .load() had been removed in 3.0 so i tried to use $.post() because I thougt that might work but it sadly didn't...
// but I kept the .load() incase it'd be useful
/*$('#film_form').load('formular-send.php', {
film_mail: mail,
film_nr: nr,
film_antal: antal,
film_namn: namn,
film_adress: adress,
film_ort: ort,
film_postnr: postnr,
film_medelande: medelande,
film_submit: submit,
emne: emne
});*/
});
} else {
}
})
PHP
<?php
$filmmail = $_POST['film_mail'];
?>
If there is anything else that is needed i'd be happy to post it to.
I think $('#emneid').val() returns something different than 'film' and your listener is never attached.
Can you please double check the returned value of $('#emneid').val();
In addition of other comments, I think you need to add the correct name for you button or your PHP form will not work.
<?php
$filmmail = $_POST['film_mail']; //for the moment your need to put $_POST['mail'] because your button is named mail instead of film_mail
?>
Please also take care in production / later use, don't use directly $_POST or your code will be vulnerable from some SQL injection and so on. Take a look at htmlspecialchars function.
Edit :
I think you can just use HTML form and php to post your data, without posting it via JS/Jquery. If you want to have some data validation before sending it, you can just call an event before submit like described in this post : (Validate form before submit jquery)
I think you maybe have a problem with your selector to trigger the function, I don't know the submit function but maybe try with on('submit') or at least it will work with on('click').
$(document).on('click', '#film_submit button[type=submit]', function(e) {
var isValid = $(e.target).parents('form').isValid();
if(!isValid) {
e.preventDefault(); //prevent the default action
}
});
<button> does not have attribute type, but <input> has, try change <button> to <input>
UPD
Where is the tag with id of #emneid?
Try this. Please replace your HTML with my HTML code.
<div id="film" class="hidden" >
<form id="film_form" action="formular-send.php" method="post">
<input id="film_mail" type="text" name="film_mail" placeholder="Mail adress">
<input id="film_nr" type="number" name="film_nr" min="1">
<input id="film_antal" type="number" name="film_antal" min="1">
<input id="film_namn" type="text" name="film_namn" placeholder="Namn">
<input id="film_adress" type="text" name="film_adress" placeholder="Adress">
<input id="film_ort" type="text" name="ort" placeholder="Ort">
<input id="film_postnr" type="text" name="film_ort" placeholder="Postnummer">
<textarea id="film_medelande" name="film_medelande" placeholder="Medelande"></textarea>
<button id="film_submit" type="submit" name="submit">Skicka</button>
<div class="error-mesage" ></div>
</form>
</div>

Deleting value="Comment?" as soon as it is clicked from the input box

I created an input box and says "comments?" before the user enters anything in it.Code;
<input type="text" name="saysome" value = "comments?"/>
But, i want to delete this "comments?" as soon as it is clicked.I am trying to do input box just like the search box in here, actually exaclty same. How can i do that?Can it be done by only javascipt? :(
Thanks
You can use the html5 placeholder attribute found here:
HTML5 Specs
For example:
<input type="text" name="saysome" placeholder = "comments?"/>
You could also take a javascript approach for browsers that do not support HTML5.
Simple method that will clear it anytime the box has focus, and not if the user has entered anything into it
<input type="text" name="TB" value="Please Enter.." onfocus="this.value==this.defaultValue?this.value='':null"/>
As other commenters mentioned, you should check out placeholder. To answer your question though, this method will remove the text on mouse click if the user has not already entered something. This assumes that the id of the input is textbox. You will have to change it to whatever you have or else assign the input an id.
<input id="textbox" type="text"/>
and the JS:
document.getElementById('textbox').onclick = function()
{
var box = document.getElementById('textbox');
if(box.value==box.defaulValue)box.value =='';
}
<input type="text" name="saysome" onblur="if(this.value=='') this.value='comments?';" onclick="this.value=''" value="comments?" />
See this example # http://x.co/Z2pa
Non-jquery:
onClick="clearComments()"
function clearComments() {
commentInput = document.getElementById("commentsId");
if(commentInput.value == 'comments?') {
commentInput.value = '';
}
}
Without jQuery:
Give the input an ID, and clear its value using an onclick event.
<input type="text" name="test" id="test" value="test" onclick="if(document.getElementById('test').value=='test')document.getElementById('test').value='';">
Also supports older browsers that don't use HTML 5.

Allow user to create and submit up to 5 text boxes with jquery, and parse them into one array in php?

Is it possible?
I want a user to post an array full of 1-5 pieces of data.
At first there would be only one text field on show, but on clicking a 'plus' icon next to it, it would create another text field below it for more user input.
I would also want to have a delete icon next to text boxes 2-5, to remove them if necessary.
My JQuery knowledge is limited, and I can work out how to append text boxes to a list, but not to keep track of them/delete them. Ideally I would also want to pass them as an array to php, so I can easily loop through them.
<input type="text" size="15" maxlength="15" name="1"><img src="add.png" onclick="add();">
<!-- Below is hidden by default, and each one shows on click of the add image -->
<input type="text" size="15" maxlength="15" name="2"><img src="delete.png" onclick="delete(2);">
<input type="text" size="15" maxlength="15" name="3"><img src="delete.png" onclick="delete(3);">
<input type="text" size="15" maxlength="15" name="4"><img src="delete.png" onclick="delete(4);">
<input type="text" size="15" maxlength="15" name="5"><img src="delete.png" onclick="delete(5);">
jQuery clone() is very handy for this. A small example how it could be done (working example on jsfiddle)
<ul>
<li><input type="text" name="textbox[]" /></li>
</ul>
<input type="button" id="addTextbox" value="Add textbox" />
<script type="text/javascript">
$(function(){
$('#addTextbox').click(function(){
var li = $('ul li:first').clone().appendTo($('ul'));
// empty the value if something is already filled in the cloned copy
li.children('input').val('');
li.append($('<button />').click(function(){
li.remove();
// don't need to check how many there are, since it will be less than 5.
$('#addTextbox').attr('disabled',false);
}).text('Remove'));
// disable button if its the 5th that was added
if ($('ul').children().length==5){
$(this).attr('disabled',true);
}
});
});
</script>
For the server-side part, you could then do a foreach() loop through the $_POST['textbox']
As long as you give each text box a name like "my_input[]", then when the form is submitted, PHP can get the answer(s) as an array.
$_REQUEST['my_input']; would be an array of the values stored in each text box.
Source: Add and Remove items with jQuery
Add
Remove
<p><input type="text" value="1" /></p>
<script type="text/javascript">
$(function() { // when document has loaded
var i = $('input').size() + 1; // check how many input exists on the document and add 1 for the add command to work
$('a#add').click(function() { // when you click the add link
$('<p><input type="text" value="' + i + '" /></p>').appendTo('body'); // append (add) a new input to the document.
// if you have the input inside a form, change body to form in the appendTo
i++; //after the click i will be i = 3 if you click again i will be i = 4
});
$('a#remove').click(function() { // similar to the previous, when you click remove link
if(i > 1) { // if you have at least 1 input on the form
$('input:last').remove(); //remove the last input
i--; //deduct 1 from i so if i = 3, after i--, i will be i = 2
}
});
$('a.reset').click(function() {
while(i > 2) { // while you have more than 1 input on the page
$('input:last').remove(); // remove inputs
i--;
}
});
});
</script>
You will need to create DOM elements dynamically. See how it is done for example in this question. Notice that
document.createElement
is faster then using jquery's syntax like
$('<div></div>')
Using that technick, you could create inputs like
<input name="id1"/>
<input name="id2"/>
<input name="id3"/>
<input name="id4"/>
<input name="id5"/>
On submitting your form you'll get all them in your query string like
...id1=someval1&id2=someval2&...
Having that, you could process this query as you want on server side.
<form method="POST" id="myform">
<input />
Add textbox
<input type="submit" value="Submit" />
</form>
<script type="text/javascript">
$(document).ready(function(){
$('#add_textbox').click(function(){
var form=$(this).closest('form');
var count=form.find('input').length();
form.append('<div class="removable_textbox"><input />delete</div>');
$('.delete_input').click(function(){
$(this).find('.removable_textbox').remove();
return false;
});
return false;
});
$('#myform').submit(function(){
var i=1;
$(this).find('input').each(function(){
$(this).attr('name','input-'+i);
i++;
})
});
});
</script>
<?php
if(isset($_POST['input-1'])){
$input_array=$_POST;
}
?>
something like this?
I wrote a litte jQuery plugin called textbox. You can find it here: http://jsfiddle.net/mkuklis/pQyYy/2/
You can initialize it on the form element like this:
$('#form').textbox({
maxNum: 5,
values: ["test1"],
name: "textbox",
onSubmit: function(data) {
// do something with form data
}
});
the settings are optional and they indicate:
maxNum - the max number of elements rendered on the screen
values - an array of initial values (you can use this to pass initial values which for example could come from server)
name - the name of the input text field
onSubmit - onSubmit callback executed when save button is clicked. The passed data parameter holds serialized form data.
The plugin is not perfect but it could be a good start.

How to gray out HTML form inputs?

What is the best way to gray out text inputs on an HTML form? I need the inputs to be grayed out when a user checks a check box. Do I have to use JavaScript for this (not very familiar with JavaScript) or can I use PHP (which I am more familiar with)?
EDIT:
After some reading I have got a little bit of code, but it is giving me problems. For some reason I cannot get my script to work based on the state of the form input (enabled or disabled) or the state of my checkbox (checked or unchecked), but my script works fine when I base it on the values of the form inputs. I have written my code exactly like several examples online (mainly this one) but to no avail. None of the stuff that is commented out will work. What am I doing wrong here?
<label>Mailing address same as residental address</label>
<input name="checkbox" onclick="disable_enable()" type="checkbox" style="width:15px"/><br/><br/>
<script type="text/javascript">
function disable_enable(){
if (document.form.mail_street_address.value==1)
document.form.mail_street_address.value=0;
//document.form.mail_street_address.disabled=true;
//document.form.mail_city.disabled=true;
//document.form.mail_state.disabled=true;
//document.form.mail_zip.disabled=true;
else
document.form.mail_street_address.value=1;
//document.form.mail_street.disabled=false;
//document.form.mail_city.disabled=false;
//document.form.mail_state.disabled=false;
//document.form.mail_zip.disabled=false;
}
</script>
EDIT:
Here is some updated code based upon what #Chief17 suggested. Best I can tell none of this is working. I am using value as a test because it works for some reason
<label>Mailing address same as residental address</label>
<input name="checkbox" onclick="disable_enable()" type="checkbox" style="width:15px"/><br/><br/>
<script type="text/javascript">
function disable_enable(){
if (document.getElementById("mail_street_address").getAttribute("disabled")=="disabled")
document.form.mail_street_address.value=0;
//document.getElementById("mail_street_address").removeAttribute("disabled");
//document.getElementById("mail_city").removeAttribute("disabled");
//document.getElementById("mail_state").removeAttribute("disabled");
//document.getElementById("mail_zip").removeAttribute("disabled");
else
document.form.mail_street_address.value=1;
//document.getElementById("mail_street_address").setAttribute("disabled","disabled");
//document.getElementById("mail_city").setAttribute("disabled","disabled");
//document.getElementById("mail_state").setAttribute("disabled","disabled");
//document.getElementById("mail_zip").setAttribute("disabled","disabled");
}
</script>
Unfortunately, since you're doing it in response to user input without a form being sent back to the server, you have to do it through JavaScript.
input elements in JavaScript have both readonly and disabled attributes. If you want them completely disabled, you need to use JavaScript (or a library like jQuery) to change the disabled attribute's value to "disabled".
Note that the disabled inputs will not have their values sent to the server when the form is submitted.
Deleted my other post entirely and replaced with all the code you should need:
<script type="text/javascript">
function disable_enable()
{
if(document.getElementById("checkbox").checked != 1)
{
document.getElementById("input1").removeAttribute("disabled");
document.getElementById("input2").removeAttribute("disabled");
document.getElementById("input3").removeAttribute("disabled");
document.getElementById("input4").removeAttribute("disabled");
}
else
{
document.getElementById("input1").setAttribute("disabled","disabled");
document.getElementById("input2").setAttribute("disabled","disabled");
document.getElementById("input3").setAttribute("disabled","disabled");
document.getElementById("input4").setAttribute("disabled","disabled");
}
}
</script>
and
<label>Mailing address same as residental address</label>
<input id="checkbox" onClick="disable_enable()" type="checkbox" style="width:15px"/><br/><br/>
<input type="text" id="input1" />
<input type="text" id="input2" />
<input type="text" id="input3" />
<input type="text" id="input4" />
Basically, loop through inputs, check if they're checkboxes, add event handlers...
Working sample in plain old javascript:
http://www.theredhead.nl/~kris/stackoverflow/enable-or-disable-input-based-on-checkbox.html
the code:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<title>Enable/disable input based on checkbox</title>
<script type="text/javascript">
// setup a bit of code to run after the document has loaded. (note that its set on window)
window.addEventListener('load', function(){
potential_checkboxes = document.getElementsByTagName('input');
for(i = 0; i < potential_checkboxes.length; i ++) {
element = potential_checkboxes[i];
// see if we have a checkbox
if (element.getAttribute('type') == 'checkbox') {
// initial setup
textbox = document.getElementById(element.getAttribute('rel'));
textbox.disabled = ! element.checked;
// add event handler to checkbox
element.addEventListener('change', function() {
// inside here, this refers to the checkbox that just got changed
textbox = document.getElementById(this.getAttribute('rel'));
// set disabled property of textbox to not checked property of this checkbox
textbox.disabled = ! this.checked;
}, false);
}
}
}, false);
</script>
</head>
<body>
<h1>Enable/disable input based on checkbox.</h1>
<form>
<label for="textbox_1">
Textbox 1:
<input id="textbox_1" type="text" value="some value" />
</label>
<br />
<input id=="checkbox_1" type="checkbox" rel="textbox_1" />
<label for="checkbox_1">Enable textbox 1?</label>
<hr />
<form>
</body>
</html>
The easiest way is to use JavaScript to enable or disable the form elements when the checkbox's checked status is changed.
That said, you will still need to filter for that checkbox when handling the post on the server, as some browsers will have JS turned off and thus the change will not happen

jQuery + hidden input fields

A simplified version of problem I am experiencing:
Here is my HTML form:
<form enctype="multipart/form-data" method="post" action="/controller/action">
<input type="text" name="title" id="title" value="" class="input-text" />
<input type="hidden" name="hidden_field" value="" id="hidden_field" />
<input type="submit" name="submit_form" id="submit_form" value="Save" class="input-submit" />
</form>
Here is the JavaScript:
$(document).ready(function() {
$('#submit_form').hover(function() {
$('#hidden_field').attr('value') = 'abcd';
});
});
And here is a really short version of the PHP backend:
if (isset($_POST)) {
var_dump($_POST);
}
What I do is I hover the #submit_form button for a few seconds just to make sure that the jQuery code got executed, then I submit the form and:
the $_POST['hidden_field'] is empty!
Why is that? It should contain 'abcd' as I insert it into the hidden field with jQuery on the hover event.
Correct way to set the value:
$('#hidden_field').val('abcd');
Reference: http://docs.jquery.com/Attributes/val
The statement
$('#hidden_field').attr('value') = 'abcd';
is incorrect. You should get an error there as you're assigning an rvalue (the jQuery object) to another rvalue (a string). (The assignment operator needs an lvalue (e.g. a variable) on the left.)
You probably want:
$('#hidden_field').val('abcd');
or:
$('#hidden_field').attr('value', 'abcd');
(The former is more jQuery-ish, but for this case both are equivilent.)
it is:
$('#hidden_field').attr('value','abcd');
Since these are hidden elements be sure to check these with something other that viewing the page source i.e. pressing F12, check with alert(), etc. The source of the original html page will not reflect changes made to it via javascript.

Categories