I have search before I post, but I only found questions and solutions that is showing ONE textbox if ONE checkbox is checked as in: jquery - show textbox when checkbox checked
But my form is different
<form method="post" action="actionhere">
<div id='clone_me'>
<?php
for($i=1; $i<=5;$i++) {
?>
<div>
<span id="title">Line <?php echo $i;?></span>
<input type='checkbox' name='ck_<?php echo $i;?>'/>
<input type='text' class='tx<?php echo $i;?>' name='tx[<?php echo $i;?>][]'/>
<input type='text' class='tx<?php echo $i;?>' name='tx[<?php echo $i;?>][]'/>
<input type='text' class='tx<?php echo $i;?>' name='tx[<?php echo $i;?>][]'/>
<input type='text' class='tx<?php echo $i;?>' name='tx[<?php echo $i;?>][]'/>
</div>
<?php } ?>
</div>
<input type='submit' name='submit' value='Submit'/>
<input type="button" value="Add row" class="addrow" />
</form>
<script>
$(document).ready(function() {
$('.addrow').click(function(){
var n= $("#clone_me>div").length;
var new_n=n+1;
var new_line= $('#clone_me div:first').clone().append();
$("span#title", new_line).text("Line "+new_n+" ");
//since I clone the 1st <div> therefore the cloned id must be 'ck_1', so changed it to latest id
$("input#ck_1", new_line).attr("name", "ck_"+new_n);
$("input#ck_1", new_line).attr("id", "ck_"+new_n);
$("input.tx1", new_line).attr("name", "tx["+new_n+"][]");
$("input.tx1", new_line).attr("class", "tx"+new_n);
new_line.appendTo('#clone_me');
});
});
</script>
As you can see from the code, I have a form which by default will have 5 sets of 1-checkbox-4-textbox, and user is allowed to add new set by clicking 'add row' button (which jquery will do clone).
How can I make the 4 textbox enabled once the correspond checkbox is checked? I'm not using hide() or show(). I want the user knows the textbox are there, but is disabled until user tick the checkbox.
if ($("#ck_4").is(":checked")) {
$("input#tx4).attr("readonly", false); //or enabled
I thought it will be something like that, but since user can dynamically add how many rows as he wants, how can I achieve it?
http://jsfiddle.net/aLw3T/2/
first give your checkbox a data attribute like this
<input type='checkbox' data-id="<?php echo $i;?>" name='ck_<?php echo $i;?>'/>
after this create following javascript code to handle your input/textarea fields
$(document).ready(function () {
$('input[type="checkbox"]').click(function () {
var self = $(this);
var checkboxId = self.data('id');
var checkboxChecked = self.is(":checked");
/* jQuery < 1.9 */
if (checkboxChecked) {
$('.tx' + checkboxId).attr('disabled', 'disabled');
} else {
$('.tx' + checkboxId).removeAttr('disabled');
}
/* jQuery 1.9+ */
$('.tx' + checkboxId).prop('disabled', checkboxChecked);
});
});
As long as the input fields are siblings to the checkbox you can use following jquery code:
$(document).ready(function() {
$('form').on('click', 'input[type=checkbox]', function(e) {
var checkbox = $(this);
checkbox.closest('.row').find('input[type=text]').prop('disabled',!checkbox.is(':checked'));
});
});
if you have multiple forms, change the selector used for binding of the click event.
e.g. $('form.my_form').on...
see example: http://codepen.io/lchngr/pen/zhasg/
Related
I've created a page that, based on an array from the database, creates multiple forms. Each form has an input with an 'add' button which dynamically adds new inputs (up to 10 inputs per form)
This works fine, but now I'm getting to where I want to submit andy input values added into the database. I have 2 main issues here:
The hidden input in my form <input type="hidden" name="tickerID" id="tickerID" value="<?php echo $ticker['ticker'] ?>"> has a non unique ID, so no matter which form I submit from, it has the ticker value belonging to the first form only.
Once I have that value, and serialize with any filled inputs in that form, I call addticker.php to insert. I'm inserting the ticker id and the content from the form inputs, but I need to do this as a foreach I believe, because if 5 inputs were added and filled in, I need a record for each. All 5 would have the same ticker ID and the respective content from the input.
Any help is appreciated
<?php foreach($tickerDisplays as $key => $ticker):?>
<form id="Items" method="post">
<label id="ItemLabel">Item 1: </label>
<input type="text" name="Items[]"><br/>
<button type="button" class="moreItems_add">+</button>
<input type="hidden" name="tickerID" id="tickerID" value="<?php echo $ticker['ticker'] ?>">
<input type="submit" name="saveTickerItems" value="Save Ticker Items">
</form>
<?php endforeach;?>
<script type="text/javascript">
$("button.moreItems_add").on("click", function(e) {
var tickerID = $('#tickerID').val();
var numItems = $("input[type='text']", $(this).closest("form")).length;
if (numItems < 10) {
var html = '<label class="ItemLabel">Item ' + (numItems + 1) + ': </label>';
html += '<input type="text" name="Items[]"/><br/>';
$(this).before(html);
console.log(tickerID);
}
});
</script>
<script type="text/javascript">
$("#Items").submit(function(e) {
//variables?
//var tickerID coming from <input type="hidden" name="tickerID" id="tickerID" value="<?php echo $ticker['ticker'] ?>">
//var Items[]
$.ajax({
type: "POST",
url: addticker.php,
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
</script>
addticker.php
$tickerID = $_POST[''];
$content = $_POST[''];
$addTicker = "
INSERT INTO tickerTable (tickerID, content)
values ('$tickerID', '$content');
"
$mysqlConn->query($addTicker)
I have multiple form like this:
<?php for ($i = 0; $i > $n; $i++) { ?> // n is no. of value (no limit)
<form>
<input name="<?php echo $i; ?>venue" type="text">
<input name="roster" type="text">
<input type="submit" name="btn_venue">
</form>
<?php } ?>
<form>
<input name="hospitality" type="text">
<input name="template" type="text">
<input type="submit" name="btn_hospitality">
</form>
...
...
<form>
<input name="element" type="text">
<input name="alignment" type="text">
<input type="submit" name="btn_xyz">
</form>
I want validate(field should not be blank) in all form so, how can I use validation ?
I tried jQuery validation:
<script>
$('document').ready(function () {
$('form').each(function (key, form) {
$(form).validate({
rules: {
hospitality: {
required: true
},
//...
//...
alignment: {
required: true
}
});
});
});
</script>
I have manage static name field validation but I don't idea about dynamic venue name validation.Can anyone help me ?
if only one form the easily maintain but dynamically multiple form submit validate how to validate.
at a time only one form submit but particular form field validate how it is possible?
Try this. It goes through each form and for each of them through each input (of type text) and builds a required rule for each of them. Then feeds the dynamically built rules to the validate function.
$('document').ready(function () {
$('form').each(function (key, form) {
// build the rules object dynamically
var rules = {};
// loop through each input in the form
$(form).find('input[type="text"]').each(function(idx, obj) {
// make a rule for this input
rules[obj.name] = {"required": true};
});
$(form).validate({
"rules": rules
});
});
});
Okey this is not for sure the cleanest way to do this but its the first that cross my mind.
First, edit your html, so form has id="form$i", input has id="input$i", and submit has id="$i". Also add class to submit class="validate"
<?php for ($i = 0; $i > $n; $i++) { ?> // n is no. of value (no limit)
<form id="form<?php echo $i; ?>">//so id="form2" for example
<input id="input<?php echo $i; ?>" name="<?php echo i; ?>venue" type="text">// id="input2"
<input name="roster" type="text">
<input id="<?php echo $i; ?>" class="validate" type="submit" name="btn_venue">//id="2"
</form>
<?php } ?>
JQuery which should work, I'll explain each line in code
<script>
$(function () {
$(".validate").click(function () { //this is call for each click button with class validate
var id = $(this).attr('id');//getting id of the clicked element which is $i
var formid = 'form' + id;//creating new var formid which will target formid (for example: in first loop $i=1, so id=1, and formid=form1)
var input = 'input' + id;//creating input which value will be input$i
$('#' + formid).on('submit', function (e) {//on form submit validate function
if ($(#input).value == '') {
return false;
} else {
return true;
}
});
});
});
</script>
hope you understand logic, it might be I made mistake somewhere so take a close look..
I tried following code in which I am trying to change paragraph tag to input fields through jquery on button click. I want my values to retain in the textbox when I click the button. Unfortunately, it isn't working! Here I have tried it with just name field. Any suggestions please.
code
<div id="menu2" class="tab-pane fade">
<h3>Address Book</h3>
<p>Default delivery address</p>
<?php
$em=$_SESSION['login_email'];
$query = mysqli_query($con,"SELECT * FROM customers where email='$em'" );
while($row=mysqli_fetch_assoc($query)){
?>
<h5>Name:</h5><p class="name" id="name"><?= $row['name'] ?></p>
<h5>Email:</h5><p class="mail"><?= $row['email'] ?></p>
<h5>Telephone:</h5><p class="tele"><?= $row['phone'] ?></p>
<h5>Address:</h5><p class="addres"><?= $row['address'] ?></p>
<h5>City:</h5><p class="city"><?= $row['city'] ?></p>
<?php
}
?>
<input type="button" id="update" value="Update Address" >
</div>
Jquery
<script src="js/jquery-1.6.2.js"></script>
<script>
$(document).ready(function() {
$('#update').click(function()
var input = $("<input>", { val: $(this).text(),type: "text" });
$('#name').replaceWith(input);
input.select();
});
});
</script>
Your code works, bar two errors. Firstly, you're missing a { after the click handler function definition. Secondly, this within the #update click handler refers to the button element, yet you're trying to read the val() of the #name input, so you need to change the selector. With that in mind, try this:
$('#update').click(function() {
var $name = $('#name');
var $input = $("<input>", {
val: $name.text(),
type: "text"
});
$name.replaceWith($input);
$input.select();
});
Working example
I would also be wary of having duplicated id attributes in your page as you are defining the elements in a loop. Should there be multiple rows returned from your query, then you will have multiple elements with the same id in the document which will lead to possible errors as the HTML will be invalid.
I want to submit the form and go to the action url only if one checkbox is selected.For that I used javascript as well as php. But it's not working properly.Once I select only one checkbox and preceed after that if I go back to the same page with the given code and go for the edit option again, it is not keeping a check if more than 1 or no checkbox is checked.
I'm not using checkboxes because for the same form i've a delete button which can delete multiple enteries at one time
<form name="form1" method="post" action="">
<input type="submit" name="Edit" value="Edit" />
JavaScript
<script language=Javascript>
function changeaction()
{document.form1.action='4a2edit.php';}
</script>
Php
<?php
if(isset($_POST['Edit'])){
$checkbox = $_POST['checkbox'];
if(count($_POST['checkbox'])>1)
{
echo"<br> <Font color=red> ***More than 1 checkbox selected.Make sure that only one checkbox must be selected.***</Font>";
}
else if (count($_POST['checkbox'])==0)
{
echo"<br><Font color=red> ***No checkbox is selected.***</Font>";
}
else
{
echo "<script language=Javascript>
changeaction();
</script>";
}}
?>
Sorry, the missing code is :
<form name="form1" method="post" action="">
<?php
//Some php code
while($row = mysql_fetch_array($result))
{
echo "<input name=\"checkbox[]\" type=\"checkbox\" value=".$row['ID']."> ".$row['ID'];
}
?>
<input type="submit" name="Edit" value="Edit" />
I have created an input fields populated by ids that I will use later to make a query in my database via javascript. Using foreach loop, the fields were populated correctly by their respective ids. Using javascript I want to be able to access this ids, however, using the onclick function that is based on their class name, the values for the first and second input fields are the only fields that returns the correct id value and the rest input field values were taken from the second input field having the id value of 2 instead of returning the right id value. What is the wrong with this? How could I retrieve right id values from this input fields? Thanks a lot. Here is my code
View:
<?php
foreach($data_currencies as $row){
?>
<div class="row-fluid">
<div class="span2"><input type='checkbox' class="currency_check_box" id='chk' name='currency_id[]' value="<?php echo $row->id; ?>" /></div>
<div class="span4" style="text-color:black;"><?php echo anchor("currencies/edit_currency/$row->id/$tennant_id",$row->pretty_name);?></div>
<div class="span4" style="text-color:black;"><?php echo $row->currency_code;?></div>
<div class="btn-group span1" id="condition" data-toggle="buttons-radio" >
<?php if($row->status==1) { ?>
<input type="text" value="<?php echo $row->id; ?>" class="btn active first" id="enable"/>
<input type="text" value="<?php echo $row->id; ?>" class="btn passive" id="disable"/>
<?php }
else{ ?>
<input type="text" value="<?php echo $row->id; ?>" class="btn off" id="enable"/>
<input type="text" value="<?php echo $row->id; ?>" class="btn active on" id="disable"/>
<?php } ?>
</div>
</div>
</address>
<address>
<?php
}
?>
Javascript
<script type="text/javascript">
$(".first").click(function(){
alert($(".first").val());
});
$(".passive ").click(function(){
alert($(".passive").val());
});
$(".off").click(function(){
alert($(".off").val());
});
$(".on ").click(function(){
alert($(".on").val());
});
</script>
Output:
Clicking the input field with id value 1
Clicking the input field with id value 2
Clicking the remaining input fields gives the same outputs
The problem is that you need to use the this keyword in your js. Otherwise you will just be getting the element with the first occurence of that class. Also considering all of your input fields have the 'btn' class why don't you change your js to
$(".btn").click(function(){
//Use 'this' to get the value of the element you clicked on
alert($(this).val());
});
Note You are looping through your rows in your PHP code but each time giving the elements the same id (id="enable" and id="disabled"). This will cause multiple elements to have the same id, which will invalidate your HTML and could cause you problems later on.
Try this
$(".first").click(function(){
alert($(this).val());
});
$(".passive ").click(function(){
alert($(this).val());
});
$(".off").click(function(){
alert($(this).val());
});
$(".on ").click(function(){
alert($(this).val());
});