Jquery:How to bind dynamic button with dynamic div? - javascript

I have product catalog. I need to have for every product, a button "show product comments".After button is pressed div with comments must appear.Div must be dynamic too, so I could open a few or more divs at the same time.I need somehow to bind button and div together, maybe they must be in the same class.
<input type="button" value="Comments" id="<?php echo $productArray[$key]
["ID"];?>" class="ProductComments"/>
<div id="<?php echo $productArray[$key]["ID"];?>" class="ProductComments" style="display:none"></div>

You can use data attribute
<input type="button" value="Comments" data-id="<?php echo $productArray[$key]["ID"];?>" class="ProductComments btn"/>
<div id="<?php echo $productArray[$key]["ID"];?>" class="ProductComments" style="display:none"></div>
Script (added .btn class to the button):
$('.ProductComments.btn').click(function(){
var id = $(this).attr('data-id');
$('#'+id).toggle();
});
JSfiddle

Related

trying to loop HTML buttons using PHP and added an EventListener in JS using querySelector but only first iterated buttons are getting selected

i am looping HTML buttons using PHP and adding EventListener for those buttons in JS using querySelector but only the first set of buttons are getting selected
Need to try querySelectorAll or please suggest something to make it work
[screenshot]
<?php $query='SELECT * FROM `posts`';
$result= mysqli_query( $conn,$query);
if(!$result){
echo "query1 failed";
}
while($rows= mysqli_fetch_assoc($result)){
echo $rows['post_text'];
?>
<br>
<form method="post" action="index.php" id="form">
<button type="submit" name="like" id='like' class="button" > <i class="ion-ios-thumbs-up like icon"></i> </button>
<button type="submit" name="love" id='heart' ><i class="ion-ios-heart icon heart icon"></i></button>
<button type="submit" name="dislike" id='dislike' ><i class="ion-ios-thumbs-down dislike icon"></i></button>
</form>
<br>
<?php
}
?>
<script>
document.querySelector('.like').addEventListener('click', function fn(e) {
e.preventDefault();
document.querySelector('.like').style.color='#3483e6';
document.querySelector('.dislike').style.color='#555';
document.querySelector('.heart').style.color='#555';
});</script>
I want all the buttons under all post should behave like first set of buttons
Check Official Documentation The Document method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors.

Select an ID from a parent element in JQuery

I want to access the id of the parent element. This code I am using and it's not working
var tag_id= $('.tag').closest('.tag').attr('id');
alert(tag_id)
This is my html
<div class='tag' id='<?php echo "$id";?>'>
<span class='tagName' id='<?php echo "$tag_name";?>'>Something</span>
</div>
I am not using .click() or .hover()
Probably the html div is in a while loop so 10 records will come from the database and it shows the same id for all records
EDIT:
I have another var but I didn't include this is it:
var tag_name = $('.tag').children('.tagName').attr('id');
its the name of the tag even though it's coming same for all tags
I tried the code from the answer for the second one and it didn't work
Html:
<div class='tag' id="<?php echo $id;?>">
<span class='tagName' id="<?php echo $tag_name;?>">Something</span>
</div>
Jquery
$('.tag').find('.tagName').attr('id'); // get child id
$('.tag').attr('id'); // parent id
Try this :
var tag_id= $('.tag').attr('id');
alert(tag_id)

jQuery/ajax form submitting not working with multiple forms + modals not closing

I have a page on my site where I got n+1 forms (n being the number of images on the site)
I have this piece of javascript to submit the forms without the user seing it directly:
$('#commentform').on('submit', function(){
$.post($(this).attr('action'), $(this).serialize(), function(response){
var imgid = $(this).find("input[name='imageid']").val();
$('#comment-'+imgid).modal('hide');
},'json');
return false;
});
That code will submit the form in a modal like this one:
<div id='comment-<?php echo $image->id; ?>' class='modal hide fade' tabindex='-1' role='dialog' aria-labelledby='myModalLabel' aria-hidden='true'>
<div class='modal-header'>
<button type='button' class='close' data-dismiss='modal' aria-hidden='true'>×</button>
<h3 id='myModalLabel'>Tilføj kommentar til billede <?php echo $orig_name; ?></h3>
</div>
<form action="<?php echo base_url(); ?>order/do_updateComment/<?php echo $image->id; ?>" method="POST" id="commentform">
<div class='modal-body'>
<textarea name="comment" rows="3" class="span6" placeholder="Skriv din kommentar her..."><?php echo $image->comment; ?></textarea>
<input type="hidden" name="imageid" value="<?php echo $image->id; ?>" />
</div>
<div class='modal-footer'>
<button class='btn' data-dismiss='modal' aria-hidden='true'>Luk</button>
<input type="submit" name="submit" class='btn btn-primary' value="Gem kommentar" />
</div>
</form>
</div>
This works perfect for the first form on the page - all the rest gets submitted the wrong way (with a redirect to the submission page)
What am I missing here? I am suspecting it to be because of the use of id="commentform" on all of the forms, but how else could this be done? I got one form on the site that needs to be submitted the normal way.
Also on a side-note, I want to close the modal once the submit has finished, which should be done with these lines of code:
var imgid = $(this).find("input[name='imageid']").val();
$('#comment-'+imgid).modal('hide');
inside the javascript (complete is in the top of the question)
However, that does not work either.. The modal stays open..
I am running the whole thing on Bootstrap 2.x with jquery 1.9.0
The reference to $(this) is dropped when you're in the callback. Save the reference outside of the post and it should work.
I am suspecting it to be because of the use of id="commentform" on all of the forms
Correct, ids must be unique. Using classes is the common way to select multiple similar elements.

Inaccurate retrieval of values from an input fields using javascript referenced by inputs class names

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());
});

Display a hidden div after a html form submit to show output

I have a html form to collect name and place and after user submit the form, the out will display at bottom of the page using PHP echo
My requirement is,
hide the output div before the form submit and after user enter data and submit, I have to make output div visible to display form output using PHP echo.
Here is my HTML code:
<div class="main">
<form id="main" name="main" action="#text" method="post">
<div class="input">
<div id="name">
<div class="block">
<div class="input-quest">Your Name</div>
<div class="input-resp"><span><input class="textbox" id="nm" name="nm" type="text" value="" /></span>
</div>
</div>
</div>
<div id="place">
<div class="block">
<div class="input-quest">Your Place</div>
<div class="input-resp"><span><input class="textbox" id="pl" name="pl" type="text" value="" /></span>
</div>
</div>
</div>
</div>
<div class="submit">
<input id="generate" type="submit" name="script" value="generate" />
<input type="submit" id="clear" name="clear" value="clear" />
</div>
</form>
<div class="output">
<?php $name = $_POST['nm']; $place = $_POST['pl']; echo "Hello, I am $name and I am from $place"; ?>
</div>
</div>
It contain the PHP echo codes at output div section.
I have searched for solution in previous questions and tried below methods mentioned there:
1.Added a inline CSS tag for output div to hide it
<div id="output" style="display: none;">
<!-- echo php here -->
</div>
and added JavaScript to call function during submit
$('main').submit(function(){
$('#output').show();
});
It didn't work.
2.Tried with below JavaScript code
$('main').submit(function(e){
$('#output').show();
e.preventDefault();
});
It didn't work.
3.Removed inline CSS for output div to hide and added the same to my CSS stylesheet
<div id="output">
and in stylesheet
#output{
display:none;
}
and used below JavaScript code on submit
$('main').submit(function(){
$('#output').css({
'display' : 'block'
});
});
It didn't work.
Added a onclick function along with the form submit
and submit button code:
<input id="generate" type="submit" name="script" value="generate" onclick="showoutput()"/>
and JavaScript:
showoutput(){
$('#output').slideDown("fast");
}
and with
showoutput(){
$('#output').show();
}
It didn't work.
Please suggest a solution to do this.
I'm not sure why you need to use js/css for this at all. Just check if the variables were posted, and if they were, echo them (you'd have to set your form action to point to the same page):
<?php if (!empty($_POST['nm']) && !empty($_POST['pl'])) { ?>
<div class="output">
Hello, I am <?php echo $_POST['nm']; ?>, and I am from <?php echo $_POST['pl']; ?>
</div>
<?php } ?>
If you just want to display the name and place in div.output, without actually submitting the form, you could do:
$('#main').submit(function(e) {
e.preventDefault(); // prevent form from being submitted
$('div.output').text('Hello, I am ' + $('#nm').val() + ', and I am from ' + $('#pl').val());
});
Here's a fiddle
<?php if(isset($_POST['nm'])) { ?>
<div class="output">
<?php $name = $_POST['nm']; $place = $_POST['pl']; echo "Hello, I am $name and I am from $place"; ?>
</div>
<?php } ?>
Create a separate page to process your form using javascript/jquery (ajax), and have it return the info you want, hide the form and show the .output div.
PHP Page:
<?php
$name = $_POST['nm'];
$place = $_POST['pl'];
echo "Hello, I am ".$name." and I am from ". $place;
?>
The javascript/jquery would catch that as responseText and then use innerHTML on your .output div to put that responseText. You'd then use the JS/Jquery to hide the form and show the .output
You can actually accomplish this entirely with php. The simplest method that I would use would be to make a hidden input with a given value. Once the user submits the form, that variable will exist and you can grab it in your php.
First you need to change the entire page to .php, and echo all of your html. then in the form, set the action to the name of the page so that it will send the variables to itself and then you can deal with them on the same page.
add this to the html:
<input type='hidden' name='display' value='display' />
In your php, add:
if (isset($_POST['display']){
echo "make the div here";
}else{
//don't show the div
}

Categories