Checkbox with Jquery map function? - javascript

I have the following code,
...
<input type="hidden" name="unchecked" id="unchecked" value="" />
<?php
$ind = 1;
foreach($array as $v){
?>
<input class="checkbox checked" id="checked_<?php echo $ind; ?>" type="checkbox" value="<?php echo $value['id']; ?>"/>
<?php
$ind++;
}
?>
...
I want to store checkbox values as comma seperated in hidden box. so i tried with the following jquery ,
<script type="text/javascript">
$(function(){
$("input.checked").click(function(){
//alert($(this).val());
$("input#unchecked").val($.map($("input[id^='checked_']"), function( item ) {
return $(item).val();
}).join(","));
});
});
</script>
The above script stores all values of checkbox when i click any one of check box. what i done wrong on this. kindly advice

Change
$("input[id^='checked_']")
to
$("input[id^='checked_']:checked")
Or use the below:
Select the checked: $("input[id^='checked_']").is(':checked')
Select the unchecked: $("input[id^='checked_']").not(':checked')

Related

multiple checkbox sum and totals in php-loop

my problem is to get a dynamic total for each checkbox group coming from a PHP loop
unique array-items comes from mysql database loop
<?php
$price_list = array(1, 7, 8, 10, 12, 15);
foreach($price_list AS $price){ ?>
<div>
<span>Price-Group <?php echo $price;?></span>
<form method="post" action="">
<input type="text" value="20.50" id="price<?php echo $price;?>"><br>
Option 1<input type="checkbox" value="1.50" data-id="<?php echo $price;?>"><br>
Option 2<input type="checkbox" value="2.50" data-id="<?php echo $price;?>"><br>
Option 3<input type="checkbox" value="3.50" data-id="<?php echo $price;?>"><br>
<input type="text" id="total<?php echo $price;?>" value="20.50">
</form>
</div>
<hr>
<?php } ?>
and here is my problem jquery-code (i need a dynamic total)
<script>
$('input:checkbox').change(function(){
var id = $(this).attr('data-id');
var total = parseFloat($('#price'+id).val());
$('input:checkbox:checked').each(function(){
total += isNaN(parseFloat($(this).val())) ? 0 : parseFloat($(this).val());
});
$('#total'+id).val(total);
});
</script>
OK, I spotted a problem in your Javascript. In the middle you do:
$('input:checkbox:checked').each(function () {....});
and this function is therefore applied to all checked checkboxes. You only want to apply the function to checked checkboxes in the pricegroup, to which the checkbox that changed belongs. Something like this:
$('#form' + id + ' input:checkbox:checked').each(function () {....});
Now you don't have a form id, so I had to add that. See: code example.
Note that you don't have to give each checkbox an individual data-id, because from them you can access the form id. For instance, when a checkbox changed:
var id = $(this).parent().attr('id');
would give you the whole form id.

Unable to get button value with loop Jquery

I am working with jquery and PHP,I want to display "buttons" according to database value(dynamic) and want to get button values in jquery, I am using "input type hidden", But right now getting value="1"(static), But I want to get "correct" value (if I select button 2 then 2 value should get in jquery)
Here is my HTML code
<?php $j=$records['start_range'];
$max= $records['end_range'];
for($i=$j;$i<=$max; $i++) { ?>
<button class="btn btn-scale btn-scale-asc-<?php echo $i; ?>">
<?php echo $i; ?>
<input type="hidden" <?php if($records['IsRatingQuestion']=="" || empty($records['IsRatingQuestion'])){ ?>name='ques_<?php echo $records['ques_id']; ?>' <?php } else{ ?>name='rangeR_<?php echo $records['ques_id']; ?>' <?php } ?> id="ratings" value="<?php echo $i; ?>">
</button>
<?php } ?>
Here is the script, Where I am wrong?
<script>
$(document).ready(function(){
$("#next1").click(function(){
var rating =$("#ratings").val();
alert(rating);
});
});
</script>
Before anything else, you need to remove input from inside that button. It's not a valid HTML.
Moreover, as mentioned in the comments, you cannot have the same id for all inputs, so I'd just remove it.
How about something like this:
$(document).ready(function() {
$('.item').each(function() {
var $button = $(this).find('button')
var $input = $(this).find('input')
$button.click(function() {
alert($input.val())
})
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="item">
<button>1</button>
<input type="hidden" value="1">
</div>
<div class="item">
<button>2</button>
<input type="hidden" value="2">
</div>
<div class="item">
<button>3</button>
<input type="hidden" value="3">
</div>
<div class="item">
<button>4</button>
<input type="hidden" value="4">
</div>
As far as I am understanding, you just want to show the value of the dynamic button using jquery. For this you just need to pass the value to the button using data attribute and then you can get the value using jquery.
<?php $j=$records['start_range'];
$max= $records['end_range'];
for($i=$j;$i<=$max; $i++) {
echo '<button class="get-value" data-value="'.$i.'">Button '.$i.'</button>';
} ?>
<input type="text" id="show-value">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(document).on('click', '.get-value', function(){
var button_value = $(this).data('value');
$('#show-value').val(button_value)
});
});
</script>
I don't think putting an <input> inside of a <button> is valid html (although it seems to work?). Instead you can just assign those values as attributes of the button itself. Also ids have to be unique, so if you have a bunch of buttons with the same id, that is also invalid. I tend to stay away from ids and just use classes to avoid this.
Also, rather than having a bunch of choppy php, you can build a single string of html and echo it back all at once. By using double qoutes " on the outside of a string, you can use single quotes ' on the inside and drop variables right into the string without escaping or concatenating anything. Although you have to wrap associative arrays in brackets {} for it to parse correctly. PHP strings.
I'm guessing $name isn't a static variable, but without seeing the rest of your code, this is just an example:
<?php
$html = "";
$name = ($records["IsRatingQuestion"] == "" || empty($records["IsRatingQuestion"])) ?
"ques_{$records["ques_id"]}" :
"rangeR_{$records["ques_id"]}";
for($i = $records["start_range"]; $i <= $records["end_range"]; $i++) {
$html .= "<button class='btn btn-scale btn-scale-asc-$i ratings' name='$name'>$i</button>";
}
echo $html;
?>
$('.btn.ratings').on('click', function() {
//$(this).text() = $i
//$(this).attr('name') = $name
});

Getting input value that has its own iterated button upon click

I've successfully added an iterator to my php foreach loop so that I can create a unique button for each row in my table.
<?php $i = 1;?>
#foreach($getPromoCodes as $codes)
<input type="hidden" name="promo_code_id" id="promo_code_id[{{$i}}]" class="promo_code_id" value="{{ $codes->promo_codet_id }}">
<?php $i++;?>
#endforeach
However, I can't figure out, once the button is pressed, how to get the value of the input from the clicked button. This being due to the uniqueness of each button with the iterator.
var promo_codet_id = document.getElementsByClassName("promo_code_id");
This returns undefined when I console log it.
How do I need to change my JS for this?
You can do this way:
<div class="elements">
<?php $i = 1;?>
<?php foreach($getPromoCodes as $codes): ?>
<input type="hidden" name="promo_code_id" id="promo_code_id[{{$i}}]" class="promo_code_id" value="{{ $codes->promo_codet_id }}">
Link
<?php $i++;?>
<?php endforeach; ?>
</div>
jquery:
$('.elements').on('click', '.btn', function(e){
e.preventDefault();
console.log($(this).data('id'));
});
You can use this.value in a call to a javascript function:
<input type="hidden" name="promo_code_id" id="promo_code_id[{{$i}}]" class="promo_code_id" value="{{ $codes->promo_codet_id }}" onclick="doSomething(this.value); return false;">

Hide textbox if empty

I want to make this code hidden if value is null,
so if the value is empty, remove this div.
div
<?php echo "test" ?>
<input type="text" id="textfield" name"test" value="<?php echo $design_value; ?>" />
div
I can fill value with PHP so when my site load value is null.
so I need any javascript code that can hide this div if no text on a textbox.
So please try to find any simple code. You can use Javascript or jQuery or whatever you think is better for this.
get Textbox value , Check if it empty then remove div.
var getTextVal= $('#textfield').val();
if(getTextVal == ""){
$('#textfield').closest('div').remove();
}
You can use JQuery $(document).ready. This event is fired after all elements in the page have initialized and recieved their values:
$(document).ready(function() {
if ($("#textfield").val == '')
$("#textfield").hide();
});
if value == '' then hide input field by adding display property to none of that element.
You can do that by running simple javascript code as shown below,
<div id="hide">
<?php echo "test" ?>
<input type="text" name="test" id="textfield" value="<?php echo $design_value; ?>" />
</div>
<script>
var hide = document.getElementById("hide");
var input = document.getElementById("textfield")
if(input.value == ""){
hide.style.display = "none";
}
</script>
You can do it by php (it won't show any output):
<?php if ($design_value != null) { ?>
<input type="text" id="textfield" name"test" value="<?php echo $design_value; ?>" />
<?php } ?>
Or in this way (a hidden field):
<input type="<?php echo ($design_value != null) ? 'text' : 'hidden'; ?>" id="textfield" name"test" value="<?php echo $design_value; ?>"/>
In plain JavaScript:
var textField = document.getElementById('textfield');
var text = textField.value;
textField.parentNode.style.display = (text) ? 'block' : 'none';

Disabling a submit button after one click without sacrificing the functionality of the form

I have asked this question before but no one was able to give a satisfactory answer.
I have a quiz website which has four radio buttons for the four options. When the user clicks on the submit button, a PHP script executes which check whether the answer is correct or not.
What I need to do is to disable the submit button after it is pressed once. All the answers that I received in my previous question interfered with the functionality of my form (it was not getting submitted). Please give a solution which do not sacrifices the functionality of the form.
Also,if you give a Javascript code as your answer, please do help me in implementing that as I am naive in Javascript.
Here is my code:
<form action="programming_skills.php?ad=<?php echo $a; ?>" method="post" id="quizsubmit">
<tr align="center">
<?php echo $row['q_desc']; ?><br />
<input type="radio" name="ans" value="<?php echo $row['ans1']; ?>" <?php echo ($_POST['ans'] == $row['ans1'] ? 'checked' : '') ?>/>
<?php echo $row['ans1']; ?><br />
<input type="radio" name="ans" value="<?php echo $row['ans2']; ?>" <?php echo ($_POST['ans'] == $row['ans2'] ? 'checked' : '') ?>/>
<?php echo $row['ans2']; ?><br />
<input type="radio" name="ans" value="<?php echo $row['ans3']; ?>" <?php echo ($_POST['ans'] == $row['ans3'] ? 'checked' : '') ?>/>
<?php echo $row['ans3']; ?><br />
<input type="radio" name="ans" value="<?php echo $row['ans4']; ?>" <?php echo ($_POST['ans'] == $row['ans4'] ? 'checked' : '') ?>/>
<?php echo $row['ans4']; ?><br />
<tr><td><input type="submit" id="sub" value=Submit_Answer></td></tr></form></table><table border="1" align="center">
<?php
if(isset($_POST['sub']))
{
$a_value=$a;
$answer=$_POST['ans'];
$q2="select * from question where q_id=$a_value";
$r2=mysql_query($q2);
if ($row=mysql_fetch_array($r2))
$trueans=$row['true_ans'];
if ($answer==$trueans)
{
$userid=$_SESSION['user_email'];
$q1="select * from temp_score WHERE user_id='$userid'";
$rw=mysql_query($q1);
while($row=mysql_fetch_assoc($rw))
$score=$row['temp_score'];
$score=++$score;
$z="update temp_score set temp_score='$score' where user_id='$userid'";
mysql_query($z);
?>
Your answer is correct. <?php $a=++$a; ?>
Click Here for next question
<?php
}
else
{
?>Your answer is wrong. The correct answer is <i>'<?php echo $trueans; ?>'</i>.<br />
<?php $a=++$a; ?>
Click Here for next question
<?php }
}
++$a;
$a=++$a;
}
}
}
else
{
echo '<meta http-equiv="refresh" content="0; url=results.php">';
}
?>
Hi found a fiddle which might help u to prevent default click event below code is will help...
document.getElementsById("quizsubmit").onclick = function () {
this.disabled = true;
};
http://jsfiddle.net/zb8CZ/
Disable it after a timeout:
<input type="submit" id="sub" value=Submit_Answer onclick="setTimeout('document.getElementById(\"sub\").disabled=!0;',100);">
You can either use an onclick event on the submit button like this:
onclick="this.disabled='disabled';this.form.submit();"
Thus, the form gets submitted via JS.
Or better make use of the onsubmit event on the form element:
onsubmit="document.getElementById('submit_button').disabled = 'disabled';"
"submit_button" is the ID attribute of your button in this case.

Categories

Resources