javascript function inside loop not working - javascript

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.

Related

Javascript function's argument is the word "Array" instead of a mySQL row

It appears that I am facing a common beginer's problem but I haven't managed to solved it on my code.
What I want to do:
I have created a database and I am currently working on a simple UI for updating it. So, I use
One drop-down menu populated by a mySQL table
Some forms with their values changed accordingly to the drop down selection.
Code(Simplified a little):
<html>
<body>
<form method="post">
<select class="dropdown" id="dropdown_id" onChange='fillFun(this.value)' >
<option disabled selected value style="display:none"> -- select an option -- </option>
<?php
//stuff pdo connection
$pdo = new PDO("mysql:host=$servername;dbname=myDatabase", $user, $password);
try
{
$result = $pdo->query("SELECT * FROM dbTable");
foreach($result as $row)
{
echo '<option value="'.$row.'"';
echo '>'. $row['last_name'].' '. $row['first_name'].'</option>'."\n";
}
}
catch(PDOException $e) { echo 'No Results'; }
?>
</select >
</form>
<form id="forms" action="results.php" method="post">
Last Name: <input type="text" id="last_name" /><br><br>
First Name: <input type="text" id="first_name" /><br><br>
<input type="submit" />
</form>
<script>
function fillFun(fill)
{
document.getElementById('last_name').value = fill[1];
document.getElementById('first_name').value = fill[2];
}
</script>
<body>
Problem:
this.value = "Array"
After researching a little I found a couple of question with a similar problem.(For instace this one)
The thing is that I can't(or don't know how,to be precise) apply the given solution print_r() or var_dump() since I am echo-ing an option value. Another way to solve a similar problem was the use of json_encode() but after the change of
onChange='fillFun(this.value)'
with
onChange='fillFun(json_encode(this.value))'
the problem wasn't solved. On the contrary, it seems that now the fill parameter was null.(Nothing happens on change).
What am I missing here?Thanks.
Instead of referring to this.value you can pass the event object to fillFunc function and obtain the value through event.target.value.
So fillFunc will be updated to:
fillFunc(event) {
document.getElementById('last_name').value = event.target.value[1];
document.getElementById('first_name').value = event.target.value[2];
}
And pass event to your onchange handler.,
<select onchange="filFunc(event)"></select>

How to Enable dynamic textbox onclick using javascript?

I have textboxes created with DB fields and a "E" for Edit link next to it. Initially the text fields are disabled. If the user wants to modify the value from DB they would click the link and the textbox next to it will be enable. The problem is that it is modifying the first text box of the same code number. This is probably because the id attribute on text field is the same and I would like to properly identified text but have failed.
Here is my code
<input type="text" name="form_line[code]" size="10"
value='<?php echo bucks($tmp['adj_amount']); ?>' disabled="true" id="editable"/>
<a id="myedit" title="Click to Edit Adjustment Value" href="#" onclick="edit_adj();return false;">E</a>
<script type="text/javascript">
function edit_adj() {
document.getElementById("editable").disabled = false;
}
</script>
An example of output is shown below and if I click on "E" the first textbox gets enabled :(
I think this will work for you:
<?php
for ($x=0; $x<=10; $x++) {
?>
<input type="text" name="somename" size="10"
value='<?php echo "hello" ?>' disabled="true" id="editable<?php echo $x ?>"/>
<a id="myedit" title="Click to Edit Adjustment Value" href="#" onclick="edit_adj(<?php echo $x ?>);return false;">Edit</a>
<br/>
<?php
}
?>
<script type="text/javascript">
function edit_adj(id) {
document.getElementById("editable"+id).disabled = false;
}
</script>
Hope this helps!
Essentially, this is giving a unique id to each text field and passing the id into the javascript that enables the text field in question. I created a test page locally and it worked.

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

Multiple forms onclick event only working for first form

I'm sure this has been asked befor but I can't seem to find it in a search
I have multiple forms on a page generated by php all with onCick event
The problem is it only picks up the first event after that any other clicks produce same result from first click
Here is javascript
function CompareScores(form)
{
var scoreA = document.getElementById("score_A").value;
var scoreB = document.getElementById("score_B").value;
if(scoreA > scoreB){
alert('Score A is Larger ' + scoreA)
}else{
alert('Score B is Larger ' + scoreB)
}
}
And the php generating forms
<?php
while($i<=$numPrelimTeams) {
if($i!=$e) {
?>
<form action="processScores.php" method="post"><p><u><?php echo $prelimTeam[$i]; ?> --> SCORE : <input type="text" class="small" id="score_A" name="score_A" size="1"></u></p>
<input type="hidden" name="team_A" value="<?php echo $prelimTeam[$i]; ?>">
<input type="hidden" name="game" value="<?php echo $game_num; ?>">
<p class="right">Game # <?php echo $game_num; ?> ) <input type="button" value="Enter Scores" onClick="CompareScores(this.form)"></p>
<?php
}else{
?>
<p><u><?php echo $prelimTeam[$i]; ?> --> SCORE : <input type="text" class="small" id="score_B" name="score_B" size="1"></u></p>
<input type="hidden" name="team_B" value="<?php echo $prelimTeam[$i]; ?>">
</form><br><br><br>
<?php
$game_num++;
$e=$e+2;
}
$i++;
}
?>
Without knowing the inputs or seeing the result, it's hard to tell for sure, but it looks like you might be generating multiple instances of this form on the same page, giving you multiple page elements named "score_A" and "score_B". document.getElementById will then become a bit ambiguous.
Since you're already sending the form object, use that instead:
var scoreA = form.score_A.value;
...
There is essentially a single problem with your code. You have multiple instances of the same ID.
To fix it, try something like this.
<input type="text" class="small score_A" name="score_A" size="1" />
Similarly
<input type="text" class="small score_B" name="score_B" size="1" />
Now, you can write a querySelector in your JS
function CompareScores(form) {
var a = form.querySelector('.score_A').value;
var b = form.querySelector('.score_B').value;
//do something
}

Categories