Select specific radio item in foreach - javascript

I have some data witch i looping in foreach. That data is input type=radio buttons with name. How can i select specific item in foreach.
My code:
<?php foreach($items as $item): ?>
<input type="radio" name="price" value="<?= $item['id'];?>"> <?= $item['name'];?> // 15 items looped
<?php endif; ?>
Output
<input type="radio" name="price" value="1"> 10$
<input type="radio" name="price" value="2"> 20$
<input type="radio" name="price" value="3"> 30$
<input type="radio" name="price" value="4"> 40$
<input type="radio" name="price" value="5"> 50$
<input type="radio" name="price" value="6"> 60$
I have custom price buttons. When i click on on button i want to select one specific radio button in foreach.
<button>select 10$ </button>
<button>select 20$ </button>
<button>select 30$ </button>

You can add a data-* attribute to both input , button elements that are the same, use .filter() to select elements that have the same .data() value at click of button, .prop("checked", true) to select the input element matching button element .data()
$("button").click(function(e) {
$("input").filter(function(i, el) {
return $(el).data("value") === $(e.target).data("value")
}).prop("checked", true)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input type="radio" name="price" value="1" data-value="$10"> 10$
<input type="radio" name="price" value="2" data-value="$20"> 20$
<input type="radio" name="price" value="3" data-value="$30"> 30$
<input type="radio" name="price" value="4" data-value="40"> 40$
<input type="radio" name="price" value="5" data-value="$50"> 50$
<input type="radio" name="price" value="6" data-value="60"> 60$
<button data-value="$10">select 10$ </button>
<button data-value="$20">select 20$ </button>
<button data-value="$30">select 30$ </button>

If your html looks like this:
<div id="checkboxes">
<input type="radio" name="price" value="1"> 10$
<input type="radio" name="price" value="2"> 20$
<input type="radio" name="price" value="3"> 30$
<input type="radio" name="price" value="4"> 40$
<input type="radio" name="price" value="5"> 50$
<input type="radio" name="price" value="6"> 60$
</div>
<div id="buttons">
<button data-val="1">select 10$ </button>
<button data-val="2">select 20$ </button>
<button data-val="3">select 30$ </button>
<button data-val="4">select 40$ </button>
<button data-val="5">select 50$ </button>
<button data-val="6">select 60$ </button>
</div>
This jQuery javascript should work:
$('#buttons button').click(function() {
var value = $(this).data('val');
$('#checkboxes input').eq(value-1).attr('checked', true);
})
Put it all together in a jsfiddle
https://jsfiddle.net/t1z1pm8x/

For doing this simple task , use of jQuery is overkill .
this can be achived using only javascript.
<?php
$i = 0
foreach($items as $item){
?>
<input type="radio" name="price" id="i<?=$i?>" value="<?= $item['price'];?>"><?= $item['name'];?> // 15 items looped
<? $i++; } ?>
Output:
<input type="radio" name="price" id="i1" value="1"> 10$
<input type="radio" name="price" id="i2" value="2"> 20$
<input type="radio" name="price" id="i3" value="3"> 30$
<input type="radio" name="price" id="i4" value="4"> 40$
<input type="radio" name="price" id="i5" value="5"> 50$
<input type="radio" name="price" id="i6" value="6"> 60$
<button id="1" onclick="select_radio(this.id)">select 10$ </button>
<button id="2" onclick="select_radio(this.id)">select 20$ </button>
<button id="3" onclick="select_radio(this.id)">select 30$ </button>
define a function
function select_radio(id){
document.getElementById("i"+id).checked = true;
}

Check out below piece of code.
<?php foreach($items as $item): ?>
`<label><input type="radio" name="price" value="<?= $item['price'];?>"> <?= $item['name'];?></label>` // 15 items looped
<?php endif; ?>
Importantly wrap your radio buttons within label tag, because interactively this is more user friendly, as the user feels easier to click the radio buttons text instead of radio button directly.
Jquery for selecting respective button.
$("button").click(function() {
var getSelectedText = $(this).text().split(" ");
$("input[type=radio][name=price]").filter(function() { return ($(this).parent().text().trim().toLowerCase()==getSelectedText[1].trim().toLowerCase()); }).attr("checked", true);
});
here we go with you required solution.. :)
Terms Used
.split() expects one parameter 'with what string to split', here in your case it is 'space'
.filter() a callback function, this returns the callback return with limited number of results, as per requirement, in your case matching the radio buttons text.
https://jsfiddle.net/zcvt1jo4/

Related

Have an input display a text but with a different value

So I have the following form:
<form>
<input type="button" value="1" >
<input type="button" value="2">
<input type="button" value="3">
<input type="button" value="4">
<button>Create account</button>
</form>
Those values are to choose a package from a database (those are the IDs). But on the screen I don't want them to display a number but a name (basic, advanced, pro, pro+). Is it possible to have a value and display a different text?
You can use input type radio for choose a different type of value.
<form action="/action_page.php">
<label><input type="radio" name="radio" value="1"> Basic </label>
<label><input type="radio" name="radio" value="1"> Advanced </label>
<label><input type="radio" name="radio" value="3"> Pro</label>
<label><input type="radio" name="radio" value="4"> Pro + </label>
<button type="submit">Create account</button>
</form>
Use a button element:
<form>
<button type="button" value="1">Basic</button>
<button type="button" value="2">Advanced</button>
<button type="button" value="3">Pro</button>
<button type="button" value="4">Pro+</button>
<button>Create account</button>
</form>
style a placeholder or data-attribute, or a for= label.

How to transfer radio button selection from 1html to another without php

I would like to transfer radio button data from the first html to the second with Pure JavaScript Its ok if you use some jQuery.
jQuery used
1st HTML
<body>
<label for="1">
<input type="radio" name="num" id="1" checked="checked" value="1" >1
</label>
<label for="2">
<input type="radio" name="num" id="2" value="2" >2
</label>
<label for="3" >
<input type="radio" name="num" id="3" value="3" >3
</label>
<label for="4">
<input type="radio" name="num" id="4" value="4" >4
</label>
<button onclick="saveSession()">save</button>
<script type="text/javascript">
function saveSession(){
// I want to save the value of the radio button to sessionStorage here
}
</script>
</body>
In my second HTML I would like to retrieve this data and set the value of the radio buttons to the same.
2nd HTML
<body onload="type()">
<label for="1">
<input type="radio" name="num" id="1" checked="checked" value="1" >1
</label>
<label for="2">
<input type="radio" name="num" id="2" value="2" >2
</label>
<label for="3" >
<input type="radio" name="num" id="3" value="3" >3
</label>
<label for="4">
<input type="radio" name="num" id="4" value="4" >4
</label>
<script type="text/javascript">
function type(){
//I want to get the data with sessionStorage.getItem()
}
</script>
</body>
It would be better if you can also tell me how to disable the form
Thanks in advance for your time and effort!!
Adding my comments as an answer. To access the radio button value, since you're using jQuery, try this:
$('input[name="num"]:checked').val();
On the first HTML page,
sessionStorage.setItem("num", $('input[name="num"]:checked').val());
And then on the second page,
sessionStorage.getItem("num");
or, to set the value of the radio on the 2nd page with the stored value:
$('input[name="num"]').val([sessionStorage.getItem("num")]);
Here is a fiddle: https://jsfiddle.net/8or3chye/
You can add a change event handler to your radios and save a new value to the local storage on that event. Afterwards on page load you need to read the saved value of the radio from the local storage and if it exists - you find an element by id and set checked to true
<label for="1">
<input type="radio" name="num" id="1" value="1" onclick="handleClick(this);" >1
</label>
<label for="2">
<input type="radio" name="num" id="2" value="2" onclick="handleClick(this);" >2
</label>
<label for="3" >
<input type="radio" name="num" id="3" value="3" onclick="handleClick(this);" >3
</label>
<label for="4">
<input type="radio" name="num" id="4" value="4" onclick="handleClick(this);" >4
</label>
<script type="text/javascript">
function handleClick(radio) {
localStorage.setItem('numRadio', radio.value)
}
(function() {
const radioValue = localStorage.getItem('numRadio')
if(radioValue) {
const targetRadio = document.getElementById(radioValue)
targetRadio.checked = true
}
})()
</script>

Counting values from HTML radio buttons in Javascript

I have a form/questionnaire where the user must choose various options in HTML.
Javascript will then add up all the options; there are more forms that will be added up to create a grand total.
I know that I need to use parseInt and various if statements:
if option 1 is selected, return value
if option 2 is selected, return value
and so on..
HTML:
<input type="radio" name="age" id= "age1" value="0" checked> 1-25<br>
<input type="radio" name="age" id= "age2" value="5"> 26-40<br>
<input type="radio" name="age" id= "age3" value="8"> 41-60<br>
<input type="radio" name="age" id= "age4" value="10"> 60+<br>
Javascript:
calculateAge () {
var age = parseInt (document.getElementById('age1').value)
if (age = checked) return age;
console.log('age')
}
I assume you want to do a sum over all selected radio button values on click of e.g. a button.
The core of this apporach is to only select those radio buttons which are checked input[type=radio]:checked. If you have those, it's easy to use Array.prototype.reduce to boil that collection down to the sum.
calc.addEventListener('click', sumToVariable)
var sum;
function sumUp() {
let sum = [...document.querySelectorAll('input[type=radio]:checked')]
.reduce(
(acc, val) => acc + Number(val.value)
, 0
)
result.textContent = sum;
return sum;
}
function sumToVariable() {
sum = sumUp();
console.log(sum);
}
body {
font-size: 10px;
}
#result:not(:empty)::before {
content: "Sum of selected options: ";
}
<input type="radio" name="age" id="age1" value="0" checked> 1-25<br>
<input type="radio" name="age" id="age2" value="5"> 26-40<br>
<input type="radio" name="age" id="age3" value="8"> 41-60<br>
<input type="radio" name="age" id="age4" value="10"> 60+<br>
<hr />
<input type="radio" name="age2" id="age10" value="0" checked> 1-25<br>
<input type="radio" name="age2" id="age20" value="5"> 26-40<br>
<input type="radio" name="age2" id="age30" value="8"> 41-60<br>
<input type="radio" name="age2" id="age40" value="10"> 60+<br>
<hr />
<button type="button" id="calc">Calc</button>
<div id="result"></div>
You could as well do the same on change of a radio button:
radiobuttons.addEventListener('change', () => {
result.textContent = [...document.querySelectorAll('input[type=radio]:checked')]
.reduce(
(acc, val) => acc + Number(val.value)
, 0
)
}
)
body {
font-size: 10px;
}
#result:not(:empty)::before {
content: "Sum of selected options: ";
}
<div id="radiobuttons">
<input type="radio" name="age" id="age1" value="0" checked> 1-25<br>
<input type="radio" name="age" id="age2" value="5"> 26-40<br>
<input type="radio" name="age" id="age3" value="8"> 41-60<br>
<input type="radio" name="age" id="age4" value="10"> 60+<br>
<hr />
<input type="radio" name="age2" id="age10" value="0" checked> 1-25<br>
<input type="radio" name="age2" id="age20" value="5"> 26-40<br>
<input type="radio" name="age2" id="age30" value="8"> 41-60<br>
<input type="radio" name="age2" id="age40" value="10"> 60+<br>
</div>
<hr />
<div id="result"></div>
age = checked
cannot work, because age is an int, and a single equal sign is not used for comparison. Also checked is a property and not a comparable. You could use it like so:
function calculateAge () {
let age = parseInt (document.getElementById('age1').value)
if (document.getElementById('age1').checked) return age;
console.log('age')
}
Also you didnt ask a question, assuming you want to know why there is nothing returned.

how to stop a javascript function from resetting on form submit

I have a problem with my web page. I am trying to create a survey with an image and using form submit with several radio button groups. The image changes every 15 secs from img1.jpg to img2.jpg and so on and so forth and the data from the radio buttons are saved in my local database. The problem is when the image is on img2.jpg and when the user clicked submit to save it to database, the image resets to img1.jpg. What should I do so that the image doesn't reset every time on form submit?
Here is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
setInterval(function(){
_path = $('img').attr('src');
_img_id = _path.replace('img/img', '');
_img_id = _img_id.replace('.jpg', '');
_img_id++;
$('img').attr('src', 'img/img' + _img_id + '.jpg');
}, 15000);
});
</script>
</head>
<body id="page-top">
<header>
<div class="header-content">
<div class="header-content-inner">
<h1><img src="img/img1.jpg" alt="image" style="width:738px;height:444px;"></h1>
<hr>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<label>Alignment: </label>
<input type="radio" name="group1" value="5"> 5
<input type="radio" name="group1" value="4"> 4
<input type="radio" name="group1" value="3"> 3
<input type="radio" name="group1" value="2"> 2
<input type="radio" name="group1" value="1"> 1
<hr>
<label>Blend: </label>
<input type="radio" name="group2" value="5"> 5
<input type="radio" name="group2" value="4"> 4
<input type="radio" name="group2" value="3"> 3
<input type="radio" name="group2" value="2"> 2
<input type="radio" name="group2" value="1"> 1
<hr>
<label>Warp: </label>
<input type="radio" name="group3" value="5"> 5
<input type="radio" name="group3" value="4"> 4
<input type="radio" name="group3" value="3"> 3
<input type="radio" name="group3" value="2"> 2
<input type="radio" name="group3" value="1"> 1
<hr>
<label>Overall: </label>
<input type="radio" name="group4" value="5"> 5
<input type="radio" name="group4" value="4"> 4
<input type="radio" name="group4" value="3"> 3
<input type="radio" name="group4" value="2"> 2
<input type="radio" name="group4" value="1"> 1
<hr>
<input type="submit" name="submit" value="Submit">
</form>
</div>
</div>
</header>
<?php
$con = mysqli_connect("localhost","root","","survey");
# $group1 = ($_POST['group1']);
# $group2 = ($_POST['group2']);
# $group3 = ($_POST['group3']);
# $group4 = ($_POST['group4']);
if(isset($_POST['submit']))
{
mysqli_query($con,"INSERT INTO response (col1,col2,col3,col4)
VALUES ('$group1','$group2','$group3','$group4')");
mysqli_close($con);
}
?>
</body>
</html>
1.Create file called form-request.php with the following code:
<?php
$con = mysqli_connect("localhost","root","","survey");
# $group1 = ($_POST['group1']);
# $group2 = ($_POST['group2']);
# $group3 = ($_POST['group3']);
# $group4 = ($_POST['group4']);
mysqli_query($con,"INSERT INTO response (col1,col2,col3,col4) VALUES ('$group1','$group2','$group3','$group4')");
mysqli_close($con);
?>
2.This should be your index page.
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
setInterval(function(){
_path = $('img').attr('src');
_img_id = _path.replace('img/img', '');
_img_id = _img_id.replace('.jpg', '');
_img_id++;
$('img').attr('src', 'img/img' + _img_id + '.jpg');
}, 15000);
$('.header-content form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'form-request.php',
data: $('.header-content form').serialize(),
success: function (data) {
console.log(data);
}
});
});
});
</script>
</head>
<body id="page-top">
<header>
<div class="header-content">
<div class="header-content-inner">
<h1><img src="img/img1.jpg" alt="image" style="width:738px;height:444px;"></h1>
<hr>
<form action="home.html" method="post">
<label>Alignment: </label>
<input type="radio" name="group1" value="5"> 5
<input type="radio" name="group1" value="4"> 4
<input type="radio" name="group1" value="3"> 3
<input type="radio" name="group1" value="2"> 2
<input type="radio" name="group1" value="1"> 1
<hr>
<label>Blend: </label>
<input type="radio" name="group2" value="5"> 5
<input type="radio" name="group2" value="4"> 4
<input type="radio" name="group2" value="3"> 3
<input type="radio" name="group2" value="2"> 2
<input type="radio" name="group2" value="1"> 1
<hr>
<label>Warp: </label>
<input type="radio" name="group3" value="5"> 5
<input type="radio" name="group3" value="4"> 4
<input type="radio" name="group3" value="3"> 3
<input type="radio" name="group3" value="2"> 2
<input type="radio" name="group3" value="1"> 1
<hr>
<label>Overall: </label>
<input type="radio" name="group4" value="5"> 5
<input type="radio" name="group4" value="4"> 4
<input type="radio" name="group4" value="3"> 3
<input type="radio" name="group4" value="2"> 2
<input type="radio" name="group4" value="1"> 1
<hr>
<input type="submit" name="submit" value="Submit">
</form>
</div>
</div>
</header>
</body>
</html>
form-request.php should be in the same directory as index.php. When submitting the form the page will not refresh nothing will happen only the data will be inserted in the MySQL database. If you want something to happen when the form is submitted please provide me an information for it.
You are posting the form. After the post, the page reloads and the initial image is being loaded.
You need a way to pass the name of the current img that you are seeing to the server when submitting the form.
There are multiple ways you can do this. For example, you can do this by passing it to the query string and then check for it.

check all radio groups are checked

I want to know best way to check all the radio button groups are checked in a page.
My code -
<div class="radioGroup">
Question1
<input type="radio" value="1" name="group1"/>1
<input type="radio" value="2" name="group1"/>2
<input type="radio" value="3" name="group1"/>3
<input type="radio" value="4" name="group1"/>4
</div>
<div class="radioGroup">
Question2
<input type="radio" value="1" name="group2"/>1
<input type="radio" value="2" name="group2"/>2
<input type="radio" value="3" name="group2"/>3
<input type="radio" value="4" name="group2"/>4
</div>
<div class="radioGroup">
Question3
<input type="radio" value="1" name="group3"/>1
<input type="radio" value="2" name="group3"/>2
<input type="radio" value="3" name="group3"/>3
<input type="radio" value="4" name="group3"/>4
</div>
<input type="button" value="check all radio Group selected" onclick="validate();"/>
and I wrote a javascript function which works fine but I want a good solution means single selector solution.
function validate(){
var isNotSelected = false;
$(".radioGroup").each(function(i,v){
var grpName = $(this).find("input:first").attr("name");
if($(this).find("[name='"+grpName+"']:checked").val() == undefined){
isNotSelected =true;
}
});
if(isNotSelected){
alert("not all checked");
}
else{
alert("all checked");
}
}
Thanks in advance
You can do
var allChecked = !$('.radioGroup:not(:has(:checked))').length;
demonstration
Check if the number of total groups match the number of groups that contain a checked radio button, if so, all groups have been selected
$('.radioGroup').length === $('.radioGroup:has(input:checked)').length

Categories