Get the value through looping in jquery - javascript

for($i=0;$i<5;i++)
{
<h2><?php echo $value['asked_title'];?> </h2>
<input type="hidden" name="question_id" value="<?php echo $i; ?>" id="question_id" class="question_id" >
}
Jquery :
$('.question_title').click(function () {
var value = $('#question_id').val();
alert(value);
});
Friends in this code question_id will be carrying different values for the looping . Here I have writtern code to get the value according to the LOOPING on click of ahref class I would like to fetch the value of hidden value for example in the first iteration title is cow on click ahref it should alert 0 (question_id value). on click on 2nd title cat it should get alert 1 like on clicking 5 different title it should display 0-4 respectively but now onclick on different title it alerts only 0 not the other values . could any one suggest me how to achieve it .

Get the parent h2 and then next .question_id like following.
$('.question_title').click(function() {
var value = $(this).parent().next('.question_id').val();
alert(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Title 0</h2>
<input type="hidden" name="question_id" value="0" id="question_id" class="question_id">
<h2>Title 1</h2>
<input type="hidden" name="question_id" value="1" id="question_id" class="question_id">
BTW you are using same id question_id for multiple elements.

As 'id' is unique value, it will get only the first element.
Try this:
for($i=0;$i<5;i++)
{
<h2><?php echo $value['asked_title'];?> </h2>
}
Jquery :
$('.question_title').click(function()
{
alert(event.target.id);
});

For
<?php
for($i=0;$i<5;i++)
{
?>
<h2><?php echo $value['asked_title'];?> </h2>
<input type="hidden" name="question_id" value="<?php echo $i; ?>" id="question_id" class="question_id" >
<?php } ?>
And in script use
$('.question_title').click(function() {
alert($(this).attr("data-tell"));
});

You are having the same id question_id in all five hidden fields.
you can have it like this..
for($i=0;$i<5;i++)
{
echo '<h2>'.$value['asked_title'].'</h2>';
}
jquery
$('.question_title').click(function()
{
var value = $(this).data('value');
alert(value);
});

Related

How to get values from Input tag using JAVASCRIPT ,the value of the input tags are fetched from mysql database using php

the JS alert need to appear whenever i'm submitting the box,the alert message need to consists an value which is get from the input tag,the value of the input tags are fetched from mysql database using php,whenever i'm submitting the form the JS alert displays an message with the first value of the table,whenever i'm submitting the remaining form,also it gives an first value from the table without giving the related values
HOW to get it?
my code is below, check it. php while loop with html tags
<?php
include "connection.php";
$sqlll="SELECT * FROM feedback";
$result=mysqli_query($conn,$sqlll);
$count=mysqli_num_rows($result);
if($count > 0)
{
while($row=mysqli_fetch_assoc($result))
{
?>
<div class="msgshare">
<div class="contentt">
<div class="userr">
<h3><i class="fa fa-user-circle"></i><?php echo $row["username"] ?></h3>
<h5><?php echo $row["img_location"] ?></h5>
</div>
<div class="imgg">
<img src="../images/feedback/<?php echo $row["img_file"] ?>" height="400px" width="400px">
</div>
<div class="likes">
<form class="likeform" onsubmit="likeso()" method="POST" action="likes.php">
<input type="hidden" id="imgile" name="imaggg" value="<?php echo $row["img_file"] ?>">
<?php
$imga=$row['img_file'];
$sql="SELECT * FROM likes WHERE `username`='$user11' AND `image`='$imga' AND `likes`='true';";
$reslt=mysqli_query($conn,$sql);
$row1=mysqli_num_rows($reslt);
$sql3="SELECT * FROM likes WHERE `image`='$imga';";
$rslt=mysqli_query($conn,$sql3);
$count=mysqli_num_rows($rslt);
if($row1 > 0)
{
echo '<button style="cursor:pointer;" name="like" type="submit" id="likepost" class="like-btn"><i id="empty" class="fa fa-heart pink"></i></button> '.$count.' likes';
}
else
{
echo '<button style="cursor:pointer;" class="willlike" name="like" type="submit" id="likepost" class="like-btn"><i id="empty" class="far fa-heart"></i></button> '.$count.' likes';
}
?>
</form>
</div>
<div class="descriptionn">
<p><span class="desc">DESCRIPTION : </span><?php echo $row["img_description"] ?></p>
</div>
</div>
</div>
<?php
}
}
else
{
echo "<p>There is no more Feedbacks are shared...</p>";
}
?>
the following is an JAVASCRIPT code for an onsubmit event.
<script>
function likeso()
{
var iage=document.querySelector('input').value;
var val="imagge=" + iage;
alert(val);
}
</script>
If you change the function call by adding event
<form class="likeform" onsubmit="likeso(event)" method="POST" action="likes.php">
And alter the function itself to use the event
function likeso(e)
{
var iage=e.target.querySelector('input').value;
var val="imagge=" + iage;
alert(val);
}
Also, you cannot duplicate ID values so
<input type="hidden" id="imgile" name="imaggg" value="<?php echo $row["img_file"] ?>">
should be changed to ( remove ID, it's not needed )
<input type="hidden" name="imaggg" value="<?php echo $row["img_file"] ?>">
The same holds for any element to which you assign an ID - it MUST be unique. If the purpose of the ID is to facilitate easy selection in Javascript using document.getElementById then having duplicate IDs makes a nonsense of that because which element should it select? Generally you can achieve most tasks without using an ID so in many cass it is best to remove them - especially when added in a loop.

javascript function inside loop not working

I am displaying online users. When I click one of the user, corresponding user should be displayed in the text box below. I am using javascript for this, but it is taking only the first user. When I click the second user, first user is displayed in the below text box. Why is it taking only the first array?
<?php
foreach($query as $row)
{
?>
<input type="text" name="user" id="user" value="<?php echo $row->users;?> onclick="select_online()">
<?php
}
?>
<script>
function select_online()
{
var user=document.getElementById("user").value;
document.getElementById("usersonline").value=user;
}
</script>
Name:<input type="text" name="usersonline" id="usersonline">
First of all, using the same id for many elements is a mistake. You should make diverse id attribute for generated inputs.
Second, you should use this to get the value of the current element:
function select_online()
{
var user=this.value;
document.getElementById("usersonline").value=user;
}
document.getElementById("user") statement will always select the element which id attribute is equal to "user" and it will always be the same. Most probably, that is not what you want. If I understood you correctly, you want to get value of the clicked element, so as I mentioned before, you can achieve it using this expression, which points to the currently clicked element.
You should give a unique name to your inputs. You cannot reuse id="user" multiple times or javascript will not be able to find each input element.
The following would be better:
<?php
$id = 0;
foreach($query as $row) {
$id += 1;
?>
<input type="text" name="user" id="user-<?php echo "$i"; ?>" value="<?php echo $row->users;?> onclick="select_online(<?php echo "$i"; ?>)">
<?php
}
?>
<script>
// Move script outside loop
function select_online(i) {
var user = document.getElementById("user-" + i).value;
document.getElementById("usersonline").value = user;
}
</script>
Name:<input type="text" name="usersonline"id="usersonline">
As per the HTML standard, there should be unique id in a document. But in your case you are generating multiple input tags with id = user. Javascript's document.getElementById is able to get only element with id = user.
For this you can change your code like this:
<?php foreach($query as $row) { ?>
<input type="text" name="user" id="user" value="<?php echo $row->users;?>" onclick="select_online(this)">
<?php } ?>
<script>
function select_online(elm) {
var user=elm.value;
document.getElementById("usersonline").value=user;
}
</script>
Name:<input type="text" name="usersonline"id="usersonline">
Here onclick, we are passing the refferance of the input tag. So we can get the refferance of the clicked input.
<input type="text" name="user" id="user" value="<?php echo $row->users;?> onclick="select_online()">
You are setting id as user for all the users so when you use selector document.getElementById("user"), it always fetches the first row.
Never use same id for more than one element. It will always cause bugs.

How to check if a radio button is clicked?

My code looks like this:
form action="familytree.php" method="post">
<?php
foreach ($spouses as $spouse) {
if (!empty($spouse['mname'])) {
$name = $spouse['fname'].' '.$spouse['lname'].' ('.$spouse['mname'].')';
}
else {
$name = $spouse['fname'].' '.$spouse['lname'];
}
if ($spouse['ended'] == '1') {
$married = '';
$divorced = 'checked';
}
else {
$married = 'checked';
$divorced = '';
}
?>
<div class="form_section dates">
<h3><?php echo $name; ?></h3>
<p>
<input type="radio" id="married_option" name="married_divorced_options" <?php echo $married; ?> value="1"/>
<label for="edate">Married</label>
<input type="radio" id="divorced_option" name="married_divorced_options" <?php echo $divorced; ?> value="1"/>
<label for="sdate">Divorced</label>
</p>
<div class="half" style="display: inline">
<input type="text" name="sdate_<?php echo $spouse['individual_id']?>" id="sdate_<?php echo $spouse['individual_id']?>" value="<?php echo $spouse['start_date']; ?>" placeholder="Rašykite sutuoktuvių datą čia"/>
<?php echo $this->formError->error("sdate_".$spouse['individual_id'].""); ?>
</div>
<div id="divorced" class="half" style="display:none">
<input type="text" name="edate_<?php echo $spouse['individual_id']?>" id="edate_<?php echo $spouse['individual_id']?>" value="<?php echo $spouse['end_date']; ?>" placeholder="Rašykite skyrybų datą čia"/>
<?php echo $this->formError->error("edate_".$spouse['individual_id'].""); ?>
</div>
</div>
<?php
}
?>
<p class="submit">
<input class="first-btn" type="submit" id="edit-relationship" name="edit-relationship" value="Edit"/>
</p>
</form>
jQuery("#divorced_option").click(function() {
document.getElementById("divorced").style.display = "inline-block";
});
jQuery("#married_option").click(function() {
document.getElementById("divorced").style.display = "none";
});
What I would like to know is how to check if a radio button is clicked when you don't know its full name, only half of it. For example, #divorced_option is not full name, it should be something like this #divorced_option_161, #divorced_option_161... So, the code should check if the radio button that has divorced_option in its name is clicked. Is there a way to achieve this?
EDIT
It works with jQuery("[id^='married_option']").click(function(){}). But I forgot to mention in my original question that the element divorced isn't full name as well, it should be divorced_161, divorced_162, depending of the name of the radio button that is clicked. How can I hide the element that matches with the radio button?
Use the attribute starts with selector (ex. [name^="value"]):
jQuery("[id^='divorced_option']").click(function() {
document.getElementById("divorced").style.display = "inline-block";
});
jQuery("[id^='married_option']").click(function() {
document.getElementById("divorced").style.display = "none";
});
Have a look at the jQuery selectors.
The 'Attribute Contains' selector would be useful here, which means your code would be :
jQuery("[id*='divorced_option']").click(function() {
document.getElementById("divorced").style.display = "inline-block";
});
jQuery("[id*='married_option']").click(function() {
document.getElementById("divorced").style.display = "none";
});
You can select the elements based on the #divorced_option_[number] pattern while checking if they are selected like this:
$("input[id*=divorced_option]:checked");
If you would like to check wether the divorced_option substring is in the name="" attribute of the radio element, then change the id from the selector to name, like so:
$("input[name*=divorced_option]:checked");
After this, just check wether or not jQuery returned an actual element.

using jquery to find value of hidden form value

I hope someone has he answer to my problem...
I'm trying to use jquery to find the value of different hidden fields on a form. My problem is I have multiple forms appearing on the same page (items of a result set for updating) and the jquery only finds the value of the first field. When I click on the div to update the field I only get the ID of the first record.
Here is my code
repeated html
<ul class="task-container-item">
<form id="task-submit" method="post" name="form">
<input class="taskID" type="hidden" value="<?php echo $taskID;?>">
<li><?php echo $name;?></li>
<li><?php echo $date;?></li>
<li><?php echo $creator;?></li>
<li class="description"><?php echo $description;?></li>
</form>
</ul>
jquery
$(document).ready(function(){
$('.task-container-item').click(function(){
$(this).css("background","green")
$(this).css("color","#fff");
var taskID = $(".taskID").val();
alert (taskID);
});
});
Hope you can help
Thanks
Dave
You can iterate on the list of elements with given class:
var taskIDs = [];
$('.taskID').each(function() {
taskIDs.push($(this).val());
});
You'll have all the ids in the taskIDs array
update
$(document).ready(function(){
$('.task-container-item').click(function(){
$(this).css("background","green")
$(this).css("color","#fff");
var taskID = $(this) // Use the element that has been clicked on
.find(".taskID") // find the .taskID element in that
.val();
alert(taskID);
});
});
Perhaps you could have php increment the forms' inputs' id.
For instance:
<input class="taskID" type="hidden" id="taskid-1" value="<?php echo $taskID;?>">
and then for the next input
<input class="taskID" type="hidden" id="taskid-2" value="<?php echo $taskID;?>">
for(var x=0;x<?php echo $total_forms; ?>;x++){
//your processing code here
}
Try:
$('input[type=hidden]')
Then you could use .each() for each hidden field.

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

Categories