JavaScript Form Cloning - javascript

I am trying to clone simple "directors / members" form. When I hit "add member button" it clones everything the form, but it does not erases zip code field. Also, when I submit the form it does not submit the first two fields of the cloned forms. It takes values of first name and last name and assigns it to address and city and so on... So, to summarize it does not send two fields, and I think it's state and zip fields of cloned forms that give me troubles, but I can't see why.
$y=0; $clone=1; do{ ?>
<div id="<?php echo "clonedSection$clone"; ?>" class="clonedSection" >
<p style="margin-left:350px; font-size: 14px;"><label id="<?php echo "member_label$clone"; ?>" > <?php echo "Director / Member $clone"; ?></label> </p><br><br>
<p style="margin-left:370px;">First name<input style="margin: 2px; margin-left: 5px; margin-right: 5px;" type="text" name="<?php echo "member_firstname$clone"; ?>" id="<?php echo "member_firstname$clone"; ?>" value="<?php echo $split_members[$y][0];?>"> <span class="error"> <?php echo $member_errors[$y]["member_first_name"];?></span> </p>
<p style="margin-left:373px; ">Last name<input style="margin: 2px; margin-left: 5px; margin-right: 5px;" type="text" name="<?php echo "member_lastname$clone"; ?>" id="<?php echo "member_lastname$clone"; ?>" value="<?php echo $split_members[$y][1];?>"> <span class="error"> <?php echo $member_errors[$y]["member_last_name"];?></span> </p>
<p style="margin-left:350px; ">Street address<input style="margin: 2px; margin-left: 5px; margin-right: 5px;" type="text" name="<?php echo "member_address$clone"; ?>" id="<?php echo "member_address$clone"; ?>" value="<?php echo $split_members[$y][2];?>"> <span class="error"> <?php echo $member_errors[$y]["member_address"];?></span> </p>
<p style="margin-left:405px; ">City <input style="margin: 2px; margin-left: 5px; margin-right: 5px;" type="text" name="<?php echo "member_city$clone"; ?>" id="<?php echo "member_city$clone"; ?>" value="<?php echo $split_members[$y][3];?>"> <span class="error"> <?php echo $member_errors[$y]["member_city"];?></span> </p>
<p style="margin-left:402px;">State<select style="margin: 2px; margin-left: 5px; margin-right: 5px;" name="<?php echo "member_state$clone"; ?>" id ="<?php echo "member_state$clone"; ?>">
<?php //$states = listStates(statesList());
foreach($states as $value){
echo '<option >'.$value.'</option>';
} echo '<option selected>'.$split_members[$y][4].'</option>'; ?>
</select> <span class="error"> <?php echo $member_errors[$y]["member_state"];?></span> </p>
<p style="margin-left:384px;">ZIP code<input style="margin: 2px; margin-left: 5px; margin-right: 5px;" type="text" name="<?php echo "member_zip$clone"; ?>" id="<?php echo "member_zip$clone"; ?>" value="<?php echo $split_members[$y][5];?>"> <span class="error"> <?php echo $member_errors[$y]["member_zip"];?></span> </p>
</div>
<?php $y++; $clone++; } while ($y < count($split_members)); ?>
And I use the following javascript:
$(document).ready(function() {
$("#btnAdd").click(function() {
$("#btnDel").prop("disabled",false);
var num = $(".clonedSection").length;
var newNum = new Number(num + 1);
var newSection = $("#clonedSection" + num).clone().attr("id", "clonedSection" + newNum);
newSection.children(":nth-child(1)").children(":first").attr("id", "member_label" + newNum);
newSection.children(":nth-child(2)").children(":first").attr("name", "member_firstname" + newNum).attr("id", "member_firstname" + newNum).attr("value", "");
newSection.children(":nth-child(3)").children(":first").attr("name", "member_lastname" + newNum).attr("id", "member_lastname" + newNum).attr("value", "");
newSection.children(":nth-child(4)").children(":first").attr("name", "member_address" + newNum).attr("id", "member_address" + newNum).attr("value", "");
newSection.children(":nth-child(5)").children(":first").attr("name", "member_city" + newNum).attr("id", "member_city" + newNum).attr("value", "");
newSection.children(":nth-child(6)").children(":first").attr("name", "member_state" + newNum).attr("id", "member_state" + newNum).attr("value", "");
newSection.children(":nth-child(7)").children(":first").attr("name", "member_zip" + newNum).attr("id", "member_zip" + newNum).attr("value", "");
$(".clonedSection").last().append(newSection);
elem = document.getElementById('member_label' + newNum);
elem.innerHTML = "Director / Member " + newNum;
if (newNum == 12)
$("#btnAdd").prop("disabled",true);
});
$("#btnDel").click(function() {
var num = $(".clonedSection").length; // how many "duplicatable" input fields we currently have
$("#clonedSection" + num).remove(); // remove the last element
// enable the "add" button
$("#btnAdd").prop("disabled",false);
// if only one element remains, disable the "remove" button
if (num-1 == 1)
$("#btnDel").prop("disabled",true);
});
//$("#btnDel").attr("disabled","disabled");
$("#btnDel").prop("disabled",true);
var count = $(".clonedSection").length;
if (count > 1)
$("#btnDel").prop("disabled",false);
//$("#btnDel").disabled = false;
});

You're making it way more complex than needed.
If you have an input <input name="example[0]" /> and clone that, and try to make it <input name="example[1]" /> with weird increments and such, just use the array version:
<input name="example[]" value="My key will be 0" />
<input name="example[]" value="My key will be 1" />
<input name="example[]" value="My key will be 2" />
To use this again in php:
foreach($_POST['example'] as $key =>$value){
echo $key.': '.$value.'<br />';
echo $key.': '.$_POST['anotherName'][$key]; // (example for another variable)
}
As you can see, a lot less complicated and much easier to read and maintain. This way you can clone your form without having to worry about which number it is, you can easily loop through them.
If you aren't used to this, I still recommend to try this, maybe only in a small test setup. Controlling arrayed forms is a skill with a lot of value.

Related

Cant access value from the HTML dataset

I am using Dataset to get some different values when doing drag and drop from one div to another. but I am not able to access the additional attributes such as data-customerId when I call the Javascript function.
HTML with PHP dynamic data:
<fieldset id="div1" ondrop="drop(event)" ondragover="allowDrop(event)">
<legend style="color:cadetblue; border:white; width:auto; font:bold">Vacant parking spots</legend>
<?php $counter = 0; foreach ($sql_get_vacant_spots_results_ as $row) { ?>
<div id="<?php echo $counter; ?>" data-customerid="<?php echo $arr_users[0]['customer_id']; ?>" data-y="<?php echo $row['spot_no'] ?>" data-z="<?php echo $row['location_id'] ?>" style="float: left; width: 120px;height: 80px;padding: 10px;border-radius: 20px;margin: 10px;background-color: cadetblue;" draggable="true" ondragstart="drag(event)" width="88" height="31">
<labled style="color: white; font:bold; font-size:large;"><?php echo 'Spot: ' . $row['spot_no'] . ' Gate: ' . $row['parking_gate_id'] ?></label>
</div>
<?php $counter++; } ?>
</fieldset>
<fieldset id="div2" ondrop="drop(event)" ondragover="allowDrop(event)">
<legend style="color:cadetblue; border:white; width:auto; font:bold">Current parking spots of the customer</legend>
<?php $count = 0; foreach ($arr_users as $user) { ?>
<div id="<?php echo $count ?>" data-customerid="<?php echo $user['customer_id'] ?>" data-y="<?php echo $user['spot_id'] ?>" data-z="<?php echo $user['location_id'] ?>" style="float: left; width: 120px;height: 80px;padding: 10px;border-radius: 20px;margin: 10px;background-color: cadetblue;" draggable="true" width="88" height="31">
<labled style="color: white; font:bold; font-size:large;"><?php echo 'Spot: ' . $user['spot_id'] . ' Gate: ' . $user['gate_id'] ?></label>
</div>
<?php $count++; } ?>
</fieldset>
And here is the Javascript:
function drop(ev) {
const el = document.querySelector('#' +ev.dataTransfer.getData("text")); //prints: Uncaught DOMException: Failed to execute 'querySelector' on 'Document': '#33' is not a valid selector.
console.log('drop', el.dataset.customerid);
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}
Fixed by accessing the id like this:
const el = document.querySelector("[id=" + "\'" + ev.dataTransfer.getData("text") + "\'" + "]");
EDIT:
Html element id:
id="count_id<?php echo $counter; ?>"

how to select closest or next div in jquery

i have a php while loop in which there are multiple outputs of posts in whcih people can comment now i want to hide the posts comments on which submit button is clicked
this is my code
<form method="POST" action="" >
<div class="commentdiv">
<input type="hidden" name="id" id="id" class="id" value="<?php echo $pixid;?>">
<input type="hidden" name="username" id="username" value="<?php echo $activeusername;?>">
<input type="hidden" name="uid" id="uid" value="<?php echo $id3;?>">
<textarea style="" name="comment" id="comment" class="comment" placeholder=" comment here"></textarea>
<button type="button" style="background-color: Transparent;
background-repeat:no-repeat;
border: none;
cursor:pointer;
overflow: hidden;
color: #3897f0; font-weight:600;" class="submit" id="button_id">comment</button>
</div>
</form>
<div id="comments" class="comments">
<?php
$sql = "SELECT * FROM comment where post_id='$pixid' order by time2 desc limit 3";
$results = mysqli_query($con,$sql);
if (mysqli_num_rows($results)>0) {
while ($row = mysqli_fetch_assoc($results)) {
$commentid = $row['id'];
$comment = $row['comment'];
$string = covertHashtags($comment);
echo "<p class='written'>";
echo "<a href='users2?id=".$row['user_id']."' style='color:black !important;'><b>".$row['username']."</b></a>";
echo " ".$string;
$sql3 = "SELECT * FROM comment where id ='$commentid' and user_id='$id' order by comment desc limit 5 ";
$results3 = mysqli_query($con,$sql3);
if (mysqli_num_rows($results3)>0) {
echo "<div class='dropdown'>
<img src='ellipsis.png' class='dots'>
<div class='dropdown-content'>
<br><p class='delete' data-delete=".$commentid.">delete</p>
</div>
</div>";
}
else{
echo "";
}
echo "</p>";
}
}else{
echo "";
}
?>
</div>
</div>
<br><br>
<?php } ?>
this is all in a while loop so all output have same classes now if i click on submit button of first post so i want the comment section of that post to dissapear not of all the posts only that particular posts's comment div
ive tried
$(this).closest('.comments').next('.comments');
and
$(this).closest('.comments');
$(this).next('.comments');
but no luck nothing is happening in return plzz help me
The comments are in a div next to the form which contains the button.
So on click of that button, it would be:
$(this).closest("form").next(".comments").hide();

How to make JavaScript dynamic?

I want to move document.getElementById("b") checked in a loop.Is it possible? How can I make it happen?
<img class="img-responsive pic" id="picture" src="images/step1.png">
<?php
//get rows query
$query = $db->query("SELECT * FROM `template_design` WHERE `panel` = 'front'");
if($query->num_rows > 0){
while($row = $query->fetch_assoc()){
$im_id = $row['id'];
$images = "images/" .$row['image']. "";
?>
<div class="col-md-4 col-sm-4 wel-grid wow fadeInDown">
<div class="wel11">
<input type="radio" id="<?php echo 'radio_'.$im_id; ?>" name="front" onClick="changeSrc(<?php echo $im_id; ?>)">
<label for="<?php echo 'radio_'.$im_id; ?>" style="font-size:12px; cursor: pointer;">
<img id="<?php echo 'picture_'.$im_id; ?>" style="border: 1px solid #ccc;" class="img-responsive" src="<?php echo $images; ?>"></label>
</div>
</div>
<?php } } ?>
<script type="text/javascript">
function changeSrc(id) {
if (document.getElementById("radio_"+id).checked) {
document.getElementById("picture_"+id).src = "images/Ppicture3.png";
}
}
</script>
I want to repeat it in a loop ,as fradio0 i.e $front will increment, JavaScript also repeat in a loop to match each.
You can pass parameters with your id for example:
<input type="radio" id="<?php echo 'radio_'.$im_id; ?>" name="<?php echo $fname; ?>" onClick="changeSrc(<?php echo $im_id; ?>)">
and use it on script like
<script type="text/javascript">
function changeSrc(id) {
if (document.getElementById("radio_"+id).checked) {
}
}
</script>
Please try this. Pass radio id as attr id & save each images by respective id's, followed by respective id.png. Also remove onclick function from your html code.
<script type="text/javascript">
$("input:radio[name=front]").click(function() {
var id= $(this).attr('id');
document.getElementById("picture").src = "panel/front/" + id + ".png";
});
</script>

How to create select box via jquery

Hello everyone i am using a webform where with 5 input box and a select box i am giving a button when anyone click on that button a new row appear with same 5 input fields and 1 select box. I am able to display input box but unable to display select box.
How to create select box via jquery.
HTML PHP CODE
<?php
$i=1;
while($roold = mysql_fetch_array($result_ss_bill_item))
{
?>
<div id="entry<?php echo $i;?>" class="clonedInput">
<div class="col-md-6"><input class="particulares" type="text" name="particulares_<?php echo $i;?>" id="particulares_<?php echo $i;?>" required="required" value="<?php echo $roold['particulares'];?>"></div>
<div class="col-md-1"><input class="challan" type="text" name="challan_<?php echo $i;?>" id="challan_<?php echo $i;?>" required="required" value="<?php echo $roold['challan'];?>"></div>
<div class="col-md-1"><input class="qty" type="text" name="qty_<?php echo $i;?>" id="qty_<?php echo $i;?>" required="required" value="<?php echo $roold['qty'];?>"></div>
<div class="col-md-1"><input class="rate" type="text" name="rate_<?php echo $i;?>" id="rate_<?php echo $i;?>" required="required" value="<?php echo $roold['rate'];?>"></div>
<div class="col-md-1"><input class="amount" type="text" name="amount_<?php echo $i;?>" id="amount_<?php echo $i;?>" required="required" value="<?php echo $roold['amount'];?>"></div>
<div class="col-md-2">
<select class="taxtype" name="tax_<?php echo $i;?>">
<option>Vat</option>
<option>Service Tax</option>
</select>
</div>
</div>
<?php
$i=$i+1;
}
?>
<div class="col-md-12">
<button class="submit btn btn-danger" type="button" id="btnAdd" value="add section">Add New </button>
</div>
JQUERY CODE
$('#btnAdd').click(function () {
var num = $('.clonedInput').length, // how many "duplicatable" input fields we currently have
newNum = new Number(num + 1), // the numeric ID of the new input field being added
newElem = $('#entry' + num).clone().attr('id', 'entry' + newNum).fadeIn('fast'); // create the new element via clone(), and manipulate it's ID using newNum value
document.getElementById("totalrecord").value=+newNum;
newElem.find('.particulares').attr('id', 'particulares_' + newNum).attr('placeholder', 'Particulares').attr('name', 'particulares_' + newNum).val('');
newElem.find('.challan').attr('id', 'challan_' + newNum).attr('placeholder', 'challan').attr('name', 'challan_' + newNum).val('');
newElem.find('.qty').attr('id', 'qty_' + newNum).attr('placeholder', 'Qty').attr('name', 'qty_' + newNum).val('');
newElem.find('.rate').attr('id', 'rate_' + newNum).attr('placeholder', 'Rate').attr('name', 'rate_' + newNum).val('');
newElem.find('.amount').attr('id', 'amount_' + newNum).attr('placeholder', 'Amount').attr('name', 'amount_' + newNum).val('');
});
$('#addSelectBtn').click(function(){
$('#container').append('<select><option>OPTION 1</option><option>OPTION 2</option></select>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='addSelectBtn'>Add Select</div>
<div id='container'></div>
newElem.find('.taxtype').attr('id', 'taxtype_' + newNum).attr('name', 'taxtype_' + newNum).val('');
Thanks everyone,
I think you have to add the new element to your dom. The function you should use is appendChild().
For example
document.getElementById("parent").appendChild(newElem).

Adding increment to form input getting TypeError: qty_el is null

I´m trying to add increments in Magento grouped items, the code should be as follows but the javascript is returning TypeError: qty_el is null.
I think the problem should be when i pass the element id variable, but can´t solve this.
What am I missing? Is there another way to do this?
Hope someone could help me.
<div class="add-to-cart">
<div class="qty-button form-group">
<input type="text" name="super_group_<?php echo $_item->getId() ?>" id="super_group_<?php echo $_item->getId() ?>" maxlength="12" value="<?php echo $_item->getQty() * 1 ?>" title="<?php echo Mage::helper('core')->quoteEscape($this->__('Qty')) ?>" class="input-text qty group-qty form-control" />
<div class="box-container">
<div class="box-icon button-plus">
<input type="button" onclick="incre(2,'super_group_<?php echo $_item->getId() ?>')" class="qty-increase" />
</div>
<div class="box-icon button-minus">
<input type="button" onclick="decre(<?php echo json_encode ($i);?>,'super_group_<?php echo $_item->getId() ?>')" class="qty-decrease" />
</div>
</div>
</div>
</div>
<script type="text/javascript">
function incre(qty_inc,idname)
{
var qty_el = document.getElementById(idname);
var qty = qty_el.value;
if( !isNaN( qty )){
if(qty_inc>0){
qty_el.value = Number(qty) + qty_inc ;
} else {
qty_el.value++;
}
}
}
function decre(qty_inc,idname)
{
var qty_el = document.getElementById(idname);
var qty = qty_el.value;
if(!isNaN( qty ) && qty > '0') {
if(qty_inc>0){
qty_el.value = Number(qty) - qty_inc;
} else {
qty_el.value--;
}
}
}
You can try another way to increment decrement quantity on grouped products
<label for="qty"><?php echo $this->__('Quantity:') ?></label>
<a href="javascript:void(0);" onclick="var qty_el = document.getElementById('super_group_<?php echo $_item->getId(); ?>'); var qty = qty_el.value; if( !isNaN( qty ) && qty > 1 ) qty_el.value--;return false;" class="qty-decrease" > - </a>
<input type="text" pattern="\d*" name="super_group[<?php echo $_item->getId() ?>]" id="super_group_<?php echo $_item->getId(); ?>" maxlength="12" value="<?php echo max($this->getProductDefaultQty() * 1, 1) ?>" title="<?php echo $this->__('Quantity') ?>" class="input-text qty" />
<a href="javascript:void(0);" onclick="var qty_el = document.getElementById('super_group_<?php echo $_item->getId(); ?>'); var qty = qty_el.value; if( !isNaN( qty )) qty_el.value++;return false;" class="qty-increase" /> + </a>

Categories