I've read few similar questions like mine and I've tried some of the option but still did not work for my code.
Basically I have radio button where I checked it by value=\"$Id\".
The reason why it refresh to the same page is because I want it to pass new total price once the user choose their address (* the shipping fee determined by the state).
echo "<input type=\"radio\" name=\"select\" value=\"$Id\" id=\"$State\" onclick=\"test()\" > <label>$Name</label><br>";
<script>
function test(){
//got few lines of codes here
var tprice = document.getElementById("prices");
var user = document.getElementById("userid");
var b = document.querySelector('input[name="select"]:checked').value;
var tot= parseFloat(calc)+0;
var totals = parseFloat(calc) + parseFloat(tprice.value);
var userid = user.value;
window.location.href = "summary.php?tot=" + tot +"&totals="+ totals +"&userid="+ userid+"&idd="+b;
document.getElementById(b).checked = true;
</script>
you can set values in session storage on select of radio. add onclick="handleClick(this);" inside radio button.
function handleClick(myRadio) {
sessionStorage.setItem("data",JSON.stringify({"myRadioButtonId":"checked"}));
}
Now get data from local storage on document ready . And set checked attributes to that radio button.
var data = sessionStorage.getItem('data');
if(JSON.parse(data).myRadioButtonId == 'checked'){
document.getElementById("myRadioButtonId").checked = true;
}
If you want a radio button to be checked, you give it the attribute checked.
echo "<input type=\"radio\" " . $_GET['idd'] == $ID ? 'checked' : '' . " name=\"select\" value=\"$Id\" id=\"$State\" onclick=\"test()\" > <label>$Name</label><br>";
You can use localstorage or sessionstorage, cookies, or best option use php server session $_SESSION
surround your echo as form and submit onclick
<form id="myForm" method="post" action="summary.php">
echo "<input type=\"radio\" name=\"select\" value=\"$Id\" id=\"$State\" onclick=\"test()\" > <label>$Name</label><br>";
</form>
test() {
// assign to value to hidden inputs
//then submit the form
document.getElementById("myForm").submit();
}
Related
I have to use a checkbox as a preference choice, so I save it in a mysql db to have it always available. When I select the chekbox the label changes to Enabled and vice versa. When you save (submit) the page sends an allert message indicating the status of the checkbox, and save the new value in the db 0 = disabled 1 = enabled and "reload" the same page and read the new values. Now I have the problem that the scripts intervene before I can read the value from the db. Only when I reload the page the second time do I get the correct values. I inserted a page refresh but I did not solve the problem.
-js-
<script>
function checked() {
if (document.getElementById("check1").checked){
$(check1).siblings('label').html('Abled');
alert("Abled Notify");
$.get("birthdaysend.php");
} else {
$(check1).siblings('label').html('Disabled');
alert("Disabled Notify");
}
}
// function change label checked
$('#check1').click(function() {
if ($(this).is(':checked')) {
$(this).siblings('label').html('Abled');
} else {
$(this).siblings('label').html('Disabled');
}
});
function urlCheck() {
if(window.location.href=="preference.php"){
//load page = read satus
checked();
}
}
urlCheck()
</script>
-Insert in to db-
$dbox = "SELECT value FROM box WHERE id = '1'";
$dbox= $db->ExecuteScalar($dbox);
print_r($dbox);//temp
if (isset($_POST['check1']) && $_POST['check1'] == '1') {
Execute("UPDATE box SET value='1' WHERE id = '1'");
header("Refresh:0");
}else{
Execute("UPDATE box SET value='0' WHERE id = '1'");
//header("Refresh:0");
}
-Html-
<form name="preference" action="preference.php" method="POST">
<div class="col-sm-4"><label class="container" for="check1">Tag 1</label><input type="checkbox" class="checkmark" name="check1" id="check1" value="1" <?php echo ($dbox == 1 ? 'checked' : '');?>></div>
<button style="float:left; margin-left: 0px;" type="submit" class="btn btn-primary"><i class="fa fa-floppy-o"></i> Save </button>
</form>
First of all change this, make update code first and then select
if (isset($_POST['check1']) && $_POST['check1'] == '1') {
Execute("UPDATE box SET value='1' WHERE id = '1'");
}else{
Execute("UPDATE box SET value='0' WHERE id = '1'");
}
$dbox = "SELECT value FROM box WHERE id = '1'";
$dbox= $db->ExecuteScalar($dbox);
print_r($dbox);//temp
Remove Urlcheck and checked functions from javascript
In label add this code instead of tag 1
echo ($dbox == 1 ? 'Abled' : 'Disabled');
A better way to do that would be with Ajax where the code to insert the value into a database is a different page from the one with a check box. Ajax is a JavaScript Library that has a synchronous ability.W3Schools tutorial for Ajax
I have a form fontVortMetodo, which I declared as
var fM = document.forms["fontVortMetodo"];
The user has the choice to submit the form to one of three PHP pages. I let him make the choice first by radio buttons with the name select. Then he should press a button, which fires the result of the form elements to the selected page.
For this firing I used the function
function destinu() {
if (fM.elements("select")[0].checked) {
fM.action = "private_php/Zamenhofa.php";
} else if (fM.elements("select")[1].checked) {
fM.action = "private_php/intereuropeco.php";
} else if (fM.elements("select")[2].checked) {
tutm = true;
fM.action = "private_php/tutmondeco.php";
}
}
There was this error:
TypeError: fM.elements("select")[0].checked is not a function".
Maybe I should try
var destiny = getElementsByName("select")
and then proceed with if (destiny[0].checked) or if (destiny[0].checked == true).
I don’t know jQuery, which somebody advised me to use, and also for JavaScript I have no reference text. Where can I find a good tutorial for jQuery, although I prefer to do everything by using JavaScript pure?
Using pure JS
Use dataset attribute to store the action.
Use this selector [name="select"]:checked to get the checked radio button.
document.querySelector('button').addEventListener('click', function(e) {
e.preventDefault();
var checked = document.querySelector('[name="select"]:checked');
var action = checked.dataset.action;
var form = document.querySelector('#fontVortMetodo');
form.setAttribute('action', action);
var tutm = checked.dataset.tutm !== undefined;
console.log("Action: " + action);
console.log('Is tutm: '+ tutm);
//$form.submit(); // This is if you need to to submit the form.
});
<form id='fontVortMetodo' name='fontVortMetodo'>
<input type='radio' name='select' data-action="private_php/Zamenhofa.php">
<input type='radio' name='select' data-action="private_php/intereuropeco.php">
<input type='radio' name='select' data-action="private_php/tutmondeco.php" data-tutm='true'>
<button>Submit</button>
</form>
I have something like this in php:
if(isset($_POST['submit']){
$check = in_array($row['service_object_id'], $values) ? 'checked' : '';
}
echo '<input type="checkbox" class="faChkRnd" id="'.$row['service_object_id'].'" name="list[]" value="'.$row['service_object_id'].'" '.$check.'>';
Each time I press a submit button, it will check the checkboxes with values inside $check.
It's working good but I want to store the checkboxes checked in localStorage automatically after pressing the button.
I already use this script to store them after click, but it won't work automatically :
<script type = "text/javascript">
$('.faChkRnd').on('click', function() {
var fav, favs = [];
$('.faChkRnd').each(function() { // run through each of the checkboxes
fav = {id: $(this).attr('id'), value: $(this).prop('checked')};
favs.push(fav);
});
localStorage.setItem("favorites", JSON.stringify(favs));
});
$(document).ready(function() {
var favorites = JSON.parse(localStorage.getItem('favorites'));
if (!favorites.length) {return};
console.debug(favorites);
for (var i=0; i<favorites.length; i++) {
console.debug(favorites[i].value == 'on');
$('#' + favorites[i].id ).prop('checked', favorites[i].value);
}
});
</script>
Any ideas ? Thank you !
you shound check type of favorites[i].value. string or boolean !?
string :
if(favorites[i].value == "true") {
$('#' + favorites[i].id ).prop('checked',true);
}
boolean :
$('#' + favorites[i].id ).prop('checked',favorites[i].value);
example :
string : https://jsfiddle.net/utm4za2p/1/
boolean : https://jsfiddle.net/utm4za2p/3/
You can use submit method.
You have a form with the submit button and you have to change it to just a regular button.
And you should put
$('.yourForm').submit()
to the end of click handler where you save the values to the localStorage.
Because when you press the submit button it may triggered before your click handler.
You need save values first and then submit form.
I have a html table, each table row have a radio button dynamically generated. Each option in the radio button have a unique id that generated dynamically also. But this id is not yet save in the database.
How to insert the option id? And how to update the option answer in that option id? Please help me. I tried to insert the values but I have no luck
Scenario:
There's a default value for the radio button, which is "No". When the user change the default value, there's a confirmation box that will ask the user if he/she want to processed. If the user click "Ok" the default value will change into "Yes".
PHP for html table:
echo '<td id="resumeFile'.$optionId.'">' . $record_s->attachment_resume_id . '</td>';
echo '<td id="processedYes><label for="Yes">Yes</label>
<input type="radio" id="processedOptionYes'.$optionId.'" name="processedOption" value="Yes" onclick="proccessedCheck('.$optionId.',\'Yes\')"/>
<label for="No">No</label>
<input type="radio" id="processedOptionNo'.$optionId.'" name="processedOption" value="No" checked="checked" onclick="proccessedCheck('.$optionId.',\'No\')" echo $record_s->process_resume === "No" checked="checked"/>/>No</td>';
echo '</tr>';
}
echo '</table>';
}
if (isset($_POST['optionId']) && $_POST['optionId']){
$optionId = $_POST['optionId'];
$queryOptionId = $wpdb->query("INSERT INTO resume_databank(process_resume_id) VALUES ('$optionId')");
}
Hidden Form:
<form id='hiddenForm' method='POST' action=''>
<input type="hidden" id="inputHidden1" name="optionId" />
<input type="hidden" id="inputHidden2" name="optionAnswer" />
</form>
JS:
function proccessedCheck(optionId,optionAnswer){
if(optionAnswer == 'Yes'){
if (confirm('You have chosen ' + optionAnswer + ', is this correct?')){
jQuery("#processedOptionYes" + optionId).attr('disabled',true);
jQuery("#processedOptionNo" + optionId).attr('disabled',true);
var withlink = jQuery("#resumeFile"+ optionId).html();
var withoutlink = jQuery(withlink).html();
jQuery("#resumeFile"+optionId).html("").append(withoutlink);
jQuery("#inputHidden1").val(optionId);
jQuery("#inputHidden2").val(optionAnswer);
jQuery("#hiddenForm").submit();
}
}
}
Hi u can change the jquery by using like below with using a class instead of function in the input type, add a class radiods to input type= radio.
$(".radiods").click(function(){
var clickid = this.id;
if($('input:radio[name=processedOption]:checked').val() == "Yes")
{
if (confirm('You have chosen YES, is this correct?'))
{
$("#inputHidden1").val(clickid);
$("#inputHidden2").val("Yes");
}
}
});
and then use ajax to update in database,so no need of form
I dont use Jquery, but Javascript is pretty simple to read the value. It is the same as a checkbox value in that it is .checked when true.
Loop through your form fields looking for checked items
var formObj = document.getElementById('hiddenform');
for(var i = 0;i < formObj.elements.length;i++){
radiovalues[] = escape(formObj.elements[id].checked);
}
Most fields have a value, ie text, hidden, password etc
escape(formObj.elements[id].value)
The checkbox and radio doesnt have a value, you are looking for "checked" which will return true or false.
What is want is - when the checkbox is checked option no. 5 in select list will be selected and when the checkbox is unchecked option no. 0 will be selected in the select list.
The select list and the checkboxes are generated dynamically in the php code as below :
echo "<select name='coupons".$i."' id='coupons".$i."'>";
------- All Options --------
echo "</select>";
<input type='checkbox' name='myCheckbox[]' value='<?php echo $i."_".$row->id; ?>' onclick='setCCode("myCheckbox[]",<?php echo $i;?>)'>
-----------------------------------------------------------------------------
Solved the second requirement on my own now ..... thanks to all for your inputs
just added the following line in the checkAll() within the for loop
setCCode(children[i],i+1);
The javascript function :
function setCCode(checkbox_name,i)
{
var form_object = document.getElementsByName(checkbox_name+"["+i+"]");
var selname = document.getElementsByName("coupons"+i)[0];
if(form_object.checked) {
selname.selectedIndex = 5;
}
else {
selname.selectedIndex = 0;
}
}
The above issue is solved....... thanks to all
Now what i need to do is when a user checks a checkbox to select or deselect all the dynamically generated checkboxes on the form the above logic should work.
<input type='checkbox' name='checkall' onChange="checkAll(this, 'myCheckbox[]')">
<span class="chkall">Check / Uncheck All</span>
<input type='checkbox' name='myCheckbox[]' value='<?php echo $i."_".$row->id; ?>' onclick='setCCode(this,<?php echo $i;?>)'>
The javascript code i am using to select/deselect all checkboxes on form is as below :
function checkAll(parent, field)
{
var children = document.getElementsByName(field);
var newValue = parent.checked;
for (i = 0; i < children.length; i++){
if (children[i].disabled == false) {
children[i].checked = newValue;
}
}
}
function setCCode(Sender,i)
{
document.getElementsByName("coupons"+i)[0].selectedIndex = Sender.checked ? 5 : 0;
}
getElementsByName returns an array of objects. Replace the line with:
var form_object = document.getElementsByName(checkbox_name+"["+i+"]")[0];
You can pass refference to the checkbox itself as a parameter
<input type='checkbox' name='myCheckbox[]' value='<?php echo $i."_".$row->id; ?>' onclick='setCCode(this,<?php echo $i;?>)'>
function setCCode(Sender,i)
{
document.getElementsByName("coupons"+i)[0].selectedIndex = Sender.checked ? 5 : 0;
}
If you have a reference to the form that the checkbox is in, and it has a unique name in the form, then you can access it as:
form_object = form.elements[ checkbox_name + "[" + i + "]" ];
and you can also use the ternary operator to make the code more concise:
selname.selectedIndex = form_object.checked? 5 : 0;
Edit
Sorry, missed the obvious. If you pass a refereference to the checkbox in the handler, then you can also get the form (all form controls have a form property that references the form they are in). So as Jan Pfeifer suggested (abbreviated markup):
<input ... onclick='setCCode(this, <?php echo $i;?>)'>
then the script is just:
function setCCode(checkbox, i)
{
checkbox.form.elements['coupons' + i].selectedIndex = checkbox.checked? 5 : 0;
}