I have the following code:
while ($row = $result->fetch_assoc()) {
echo "<div class='competitor' style='background: ".$row['Colour'].";'>";
echo "<div class='competitorname'>".$row['CompetitorName']."</div><br>";
echo "<div class='competitorscore' id='".$row['CompetitorID']."'>";
echo"<label id='".$row['CompetitorName']."'></label></div>";
echo "<input type='button' value='Increase' id='inc' onclick='incNumber()'/>";
echo "<input type='button' value='Decrease' id='dec' onclick='decNumber()'/>";
}
The code is linked to the following script:
var i = 0;
function incNumber() {
if (i < 10) {
i++;
} else if (i = 10) {
i = 0;
}
document.getElementById('display').innerHTML = i;
}
function decNumber() {
if (i > 0) {
--i;
} else if (i = 0) {
i = 10;
}
document.getElementById('display').innerHTML = i;
}
The code creates a scoreboard. It creates a div for each team with a score for that team.
The problem I'm having is that the "Increase" and "Decrease" buttons are increasing and decreasing the score on only one team (the first one). This is because the script is looking for the label with the id='display' and linking every button to that one.
My question is, how can I create a different ID for each team that works with the script so that each increase/decrease button is linked to a different team?
Use the CompetitorID as a parameter to the increment and decrement functions to tell it which row to affect. Your label:
<label id='display".$row['CompetitorID']."'></label>
Your button onclick event:
onclick='incNumber(".$row['CompetitorID'].")'
Then your JavaScript:
function incNumber(id) {
if (i < 10) {
i++;
} else if (i = 10) {
i = 0;
}
document.getElementById('display' + id).innerHTML = i;
}
Edit
For the issue in the comments, echo a hidden field which stores the value for each team:
<input type='hidden' id='score".$row['CompetitorID']."' value='0'/>
Then remove the global var i = 0; and modify your functions similar to this:
function incNumber(id) {
// Get the score input
var scoreField = document.getElementById('score' + id);
// Get the value
var i = parseInt(scoreField.value);
if (i < 10) {
i++;
} else if (i = 10) {
i = 0;
}
// Set the visual score
document.getElementById('display' + id).innerHTML = i;
// Set the score input to the new score
scoreField.value = i;
}
You have a $row['CompetitorID'] value which is, presumably, unique. Append that to the IDs you are using.
Related
I have the following piece of code I am working on. My purpose is to be able to grab information about different users from a specific website, display the name and other info and then have a button that when clicked, prints more information. I am able to get the information and display the name and picture, but when I click the button the information is displayed at the top of the page, not under the specific button that was clicked. I want for the information to be display under each user... I am new to Javascript and learning on my own, any help is appreciated!
function getUsers(user) {
var out = "";
var i;
for (i = 0; i < user.length; i++) {
out += '' + user[i].login + '<br>'+'</br> <img src="'+user[i].avatar_url+
'" alt="Image" style="width:304px;height:228px"</br></br>'+
'<button onclick=printRepos("'+user[i].repos_url+'")>Repositories</button></br>'+'<div id="id"></div>';
}
document.getElementById("id01").innerHTML = out;
}
Printing Function
function printF(array) {
var out = "";
var i;
for (i = 0; i < array.length; i++) {
out += array[i].id+'</br>';
}
document.getElementById("id").innerHTML = out;
}
This works fine. I just made div with dynamic ids and passed it to the function
function getUsers(user) {
var out = "";
var i;
for (i = 0; i < user.length; i++) {
out += '' + user[i].login + ' <br>'+'</br> <img src="'+user[i].avatar_url+
'" alt="Image" style="width:304px;height:228px"</br></br>'+
'<button onclick=printRepos("'+user[i].repos_url+'","'+i+'")>Repositories</button></br>'+'<div id="'+ 'id' + i +'"></div>';
}
document.getElementById("id01").innerHTML = out;
}
function printRepos(array, id) {
var out = "";
var i;
for (i = 0; i < array.length; i++) {
out += array[i].id+'</br>';
}
console.log('id' + id);
document.getElementById('id' + id).innerHTML = out;
}
Add the "this" keyword as a parameter to your onclicks, to pass in the button that was clicked:
<button onclick=printRepos(this,"'+user[i].repos_url+'")>Repositories</button>
Then locate the next div after that button in your event handler:
function printF(btn, array) {
var out = "";
var i;
for (i = 0; i < array.length; i++) {
out += array[i].id+'</br>';
}
// find the div
var d = btn; // start with the button
while (d.tagName != "DIV") d = d.nextSibling; // look for the next div
d.innerHTML = out;
}
How to ensure i have a dynamic increment of Alphabets in a new cell on left side, next to each cell in a row which is dynamically created based on the option chosen in Select. This newly generated alphabet will be considered as bullet points/serial number for that particular row's text box.
jsfiddle
js code
$(document).ready(function(){
var select = $("#Number_of_position"), table = $("#Positions_names");
for (var i = 1; i <= 100; i++){
select.append('<option value="'+i+'">'+i+'</option>');
}
select.change(function () {
var rows = '';
for (var i = 0; i < $(this).val(); i++) {
rows += "<tr><td><input type='text'></td></tr>";
}
table.html(rows);
});
});
html
<select id="Number_of_position">
</select> <table id="Positions_names">
</table>
This is essentially a base26 question, you can search for an implementation of this in javascript pretty easily - How to create a function that converts a Number to a Bijective Hexavigesimal?
alpha = "abcdefghijklmnopqrstuvwxyz";
function hex(a) {
// First figure out how many digits there are.
a += 1; // This line is funky
var c = 0;
var x = 1;
while (a >= x) {
c++;
a -= x;
x *= 26;
}
// Now you can do normal base conversion.
var s = "";
for (var i = 0; i < c; i++) {
s = alpha.charAt(a % 26) + s;
a = Math.floor(a/26);
}
return s;
}
So you can do
$(document).ready(function(){
var select = $("#Number_of_position"), table = $("#Positions_names");
for (var i = 1; i <= 100; i++){
select.append('<option value="'+i+'">'+i+'</option>');
}
select.change(function () {
var rows = '';
for (var i = 0; i < $(this).val(); i++) {
rows += "<tr><td>" + hex(i) + "</td><td><input type='text'></td></tr>";
}
table.html(rows);
});
});
Heres the example http://jsfiddle.net/v2ksyy7L/6/
And if you want it to be uppercase just do
hex(i).toUpperCase();
Also - this will work up to any number of rows that javascript can handle
if i have understood you correctly, that's maybe what you want:
http://jsfiddle.net/v2ksyy7L/3/
I have added an array for the alphabet:
var alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
and then added the output to your "render" loop:
rows += "<tr><td>" + alphabet[i] + " <input type='text'></td></tr>";
I am trying to limit the number of checkboxes a user can select. These checkboxes are DOM input objects generated for each item in an array. I'm having no luck with this currently, so any help is much appreciated. Thanks!
Fiddle Here: http://jsfiddle.net/vVxM2/222/
names =["Donny","Danny","Ricky","Eric","Jamie","Bobby","Booby"];
var numberOf = names.length;
var text = "<ul>";
for (i = 0; i < numberOf; i++) {
text += "<li class='playerListItem'><label><input type='checkbox' class='playerCheckbox'>" + names[i] + "</label></li>";
}
text += "</ul>";
document.getElementById("recentPlayersContainer").innerHTML = text;
var limit = 3;
$('input.playerCheckbox').on('change', function(event) {
if($(this).siblings(':checked').length >= limit) {
this.checked = false;
}
});
Your problem is in the change event.
Instead of doing:
if($(this).siblings(':checked').length >= limit)
You should do this:
if($('.playerCheckbox:checked').length >= limit)
Also, if your limit is maximum 3 checked, then you should do:
$('.playerCheckbox:checked').length > limit
Because when the event change is raised, the current checkbox is already checked.
Your problem was found here: if($(this).parent().siblings().children(":checkbox:checked").length >= limit). You actually have two parents, so you should have added another parent() and children() function. It should look like if($(this).parent().parent().siblings().children().children(":checkbox:checked").length >= limit)
names = ["Donny", "Danny", "Ricky", "Eric", "Jamie", "Bobby", "Booby"];
var numberOf = names.length;
var text = "<ul>";
for (i = 0; i < numberOf; i++) {
text += "<li class='playerListItem'><label><input type='checkbox' class='playerCheckbox'>" + names[i] + "</label></li>";
}
text += "</ul>";
document.getElementById("recentPlayersContainer").innerHTML = text;
var limit = 3;
$('input.playerCheckbox').on('change', function() {
if ($(this).parent().parent().siblings().children().children(":checkbox:checked").length >= limit) {
$(this).attr('checked', false);
alert('You can only select 3 checkboxes.');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="recentPlayersContainer">
</div>
DEMO
names =["Donny","Danny","Ricky","Eric","Jamie","Bobby","Booby"];
var numberOf = names.length;
var text = "<ul>";
for (i = 0; i < numberOf; i++) {
text += "<li class='playerListItem'><label><input type='checkbox' class='playerCheckbox'>" + names[i] + "</label></li>";
}
text += "</ul>";
document.getElementById("recentPlayersContainer").innerHTML = text;
var limit = 3;
$('input.playerCheckbox').on('change', function(event) {
if($('input.playerCheckbox:checked').length >= limit + 1) {
alert('enough');
}
});
I have a form that consist of different form elements (radio, text, select) and is dynamically created in PHP. However, I'm trying to validate this form in JQuery based on the question type. My questions are named q1, q2,.....
$(function(){
if ($('form').length > 0) {
$('form').submit(function(e){
var len = <?php echo $numRows; ?>; // refers to the number of rows in questions table of a database
for (var i = 1; i <= len; i++ ) {
var qNum = 'q'+i;
//document.write(qNum);
if (($('input[name=' + qNum + ']:checked').length == 0) )
{
if ($('input[type=Radio][name=' + qNum + ']')) {
alert("No Selection is made for "+ qNum);
return false;
}
}
}
}); // form submit function
}// form.length
})//function
The above code handles radio buttons efficiently. However, when it comes to non radio questions it still display an alert message to that non radio question. Anyway, of handling this differently based on the question type?
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(function(){
if ($('form').length > 0) {
$('form').submit(function(e){
var answers = '';
//alert (qNum);
var i = 1;
var len = <?php echo $numRows; ?>;
$('input[type=Radio]:checked').each(function() {
if (answers !== '') {
answers += ',';
}
answers += $(this).val();
//alert(answers);
})
$('input[name=h2]').val(answers);
for (var i = 1; i <= len; i++ ) {
var qNum = 'q'+i;
//document.write(qNum);
if (($('input[name='+qNum+']:checked').length == 0) )
{
if ($('#'+qNum+'').is(':radio')) {
alert("No Selection is made for "+ qNum);
return false;
}
}
}
}); // form submit function
}// form.length
})//function
as before the below code is in a while loop . it out puts values id=pro0 then next loop through i get id=pro1 and if i have another record i get id=pro3
print "<td><input style=\"text-align:center\" type=\"text\" name=\"productitemsupdate_$num\" value=\"$row[productitems]\" size=\"5\" id=\"pro$num\"></td>";
the above code works with
var pro = document.getElementById('pro0');
what im after is a loop in java script which will take the last $num from the php from and use that for the amount of times to loop the javascript function.
something like this i think
var i=0;
while (i<=$num) {
var pro[i] = document.getElementById('pro'[i]);
if (pro[i].value == "") {
inlineMsg('pro'[i],'This cannot Be blank'[i],10);
return false;
} else {
i++;
}
}
breaks when it is false when all fields are right it is true.
if i get this working it will save me guessing how many variable to check.
i have tried this but i cant this working either
var i=0;
var pro[i] = document.getElementById('pro' + i);
for(var i = 0; i < <?php $num ?>; i++) {
if(pro[i].value == "")
alert("You entered: " + pro[i].value)
return false;
}
this works but only for the first line. if the 2nd line is emtpy and the first line is not it does not produce the alert
var i=0;
for(var i = 0; i < 3; i++) {
var pro = document.getElementById('pro' + i);
if(pro.value == "")
alert("You entered: " + pro[i].value)
return false;
}
i also changed the $num variable to a static number for my test record to see if it was my variable not being passed and it still did't work for the 2nd record any ideas
thanks
steve
working solution thanks for your help
var i=0;
var pro = [];
for(var i = 0; i < 2; i++) {
pro[i] = document.getElementById('pro' + i);
if(pro[i].value == ""){
alert("You entered: " + pro[i].value)
return false;}
}
PHP is server-side. JavaScript is client-side. If you want to insert a PHP variable into JavaScript, you have to treat your JS like HTML and use PHP to create the script. Something like this:
<!-- ... -->
<script>
var num = <?php echo $num ?>;
</script>
<!-- ... -->
Then you can use this value of num elsewhere, even in external scripts (as long as num is declared beforehand).
Edit
Your if statement in the for loop is missing braces. Try this:
var i=0,
pro[i] = document.getElementById('pro' + i);
for(var i = 0; i < <?php echo $num ?>; i++) {
if(pro[i].value == "")
{
alert("You entered: " + pro[i].value)
return false;
}
}
Make sure that this JS is actually being processed by PHP. The easiest way to do that is to put the code into an inline <script> tag.
In javascript, you concatenate strings using +. Therefore, you need to write
pro[i] = document.getElementById('pro' + i);
For your loop, that'd look something like
for(var i = 0; i < <?php echo $num ?>; i++) {
...
}
Complete code:
var i=0;
var pro = [];
for(var i = 0; i < <?php echo $num ?>; i++) {
pro[i] = document.getElementById('pro' + i);
if(pro[i].value == "") {
alert("You entered: " + pro[i].value)
return false;
}
}
If you don't need the actual array for anything, for later, you could simply do:
var i=0;
for(var i = 0; i < <?php echo $num ?>; i++) {
var pro = document.getElementById('pro' + i);
if(pro.value == "") {
alert("You entered: " + pro.value)
return false;
}
}
What ever your PHP (not my expertise), here is an example looping through: http://jsfiddle.net/UpG57/