How to insert the value of dynamically radio button using PHP? - javascript

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.

Related

how do I populate html form fields from a dynamic form dropdown

I am trying to figure out a way to fill html form fields based on the selection of a dynamic form dropdown menu.
I have been looking around and trying to tweek what I have found. So far I am up to filling one of my form fields. But have no gone off piste trying to fill all three, leaving the radio empty when I want it to pick up the 0 value on all my dummy entries and select enable (0)
<option value="<?= $row['ENABLED2'] . " - " . $row['ID2'] . " - " . $row['SOLDTO2'] ?>"> ..</option>
<?php
}
?>
</select>
...
<script>
$(document).ready(function() {
$("#ddlModel").on("change", function() {
var GetValue = $("#ddlModel").val();
const GetValueArray = GetValue.split(" - ");
var GetValueSold = GetValueArray[2];
var GetValueID = GetValueArray[1];
var GetValueEn = GetValueArray[0];
$("#SOLDTO2").val(GetValueSold);
$("#ID2").val(GetValueID);
$("#ENABLED2").val(GetValueEn);
});
});
</script>
...
<FORM id='addClient' action='process/process-addclient.php' method='post'>
<input type='text' id='ID2' name='ID2' maxlength='4' placeholder='Four Digit Sage Code' style='display:inline'>
<textarea id='SOLDTO2' name='SOLDTO2' placeholder='Client Name and Address - 6 Lines Max'></textarea>
<input type="radio" name='ENABLED2' id='enable' value='0'> <label for='enable'>Enable Client</label>
<input type="radio" name='ENABLED2' id='disable' value='1'> <label for='disable'>Disable Client</label>
In writing this out I have answered some of my own questions but I cant figure out how to get the last column (radio) to populate.
I am new to JS/JQ
The way to populate the radio field is by using the following code:
<script>
$(document).ready(function() {
$("#ddlModel").on("change", function() {
var GetValue = $("#ddlModel").val();
const GetValueArray = GetValue.split(" - ");
var GetValueSold = GetValueArray[2];
var GetValueID = GetValueArray[1];
var GetValueEn = GetValueArray[0];
$("#SOLDTO2").val(GetValueSold);
$("#ID2").val(GetValueID);
$("#ENABLED2").val(GetValueEn);
//Check radio field based on value of GetValueEn
if (GetValueEn == 0) {
$("#enable").prop('checked', true);
}
else {
$("#disable").prop('checked', true);
}
});
});
</script>

save and read the checkbox value in the db, change the status of the label

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

How to keep the radio button remain checked after the refresh

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

Get list of all checkboxes with checked and unchecked status

I have following code, to show an image along with its checkbox. It is either enabled or disabled
if($ring["status"] != '1')
echo '<td><input type="checkbox" name="ringIds[]" value="'.$ring["id"].'">'
. '<input type="image" onClick="openGalleryRing(\''.$ring['imagePath'].'\', \''.$ring['id'].'\');" src="http://thevowapp.com/iphoneapp/vowstore/rings/'. $ring['imagePath'] .'" name="checked" value="' . $ring['id'].'" data-my-info="'. $ring['ringSetName'] .'" style="width:200px; height:200px; margin-left: 10px;"></td>';
else
echo '<td><input type="checkbox" checked="checked" name="ringIds[]" value="'.$ring["id"].'">'
. '<input type="image" onClick="openGalleryRing(\''.$ring['imagePath'].'\', \''.$ring['id'].'\');" src="http://thevowapp.com/iphoneapp/vowstore/rings/'. $ring['imagePath'] .'" name="checked" value="' . $ring['id'].'" data-my-info="'. $ring['ringSetName'] .'" style="width:200px; height:200px; margin-left: 10px;"></td>';
In my javascript i am using something like
$('.updateBtn').on('click', function()
{
var checked = $('input[name="ringIds[]"]:checked').serialize();
if(checked !== '')
window.location.href = 'actions.php?j=24&' + checked;
else
alert('No Rings are selected');
});
This works, i can get all the checked checkboxes, but what i actually want is to get all hte list of checkboxes, which are checked and which are not. How can i modify this code?
Note: Only "successful controls" are serialized to the string. No
submit button value is serialized since the form was not submitted
using a button. For a form element's value to be included in the
serialized string, the element must have a name attribute. Values from
checkboxes and radio buttons (inputs of type "radio" or "checkbox")
are included only if they are checked. Data from file select elements
is not serialized.
Thus .serialize() will return only checked checkboxes whether or not you include the pseudo selector :checked.
You may want to use .each() or .map() to get the unselected checkboxes.
var unchecked = "";
$('input[name="ringIds[]"]').not(':checked').each(function() {
unchecked += (unchecked.length ? '&' + '') + this.name + '=' + this.value;
});
Or:
var unchecked = $('input[name="ringIds[]"]').not(':checked').map(function(i,v) {
return this.name + '=' + this.value;
})
.get().join('&');
Here is the code which you are looking for:
$('.updateBtn').on('click', function()
{
var check_boxes = $('input[name="ringIds[]"]').serialize();
// Try below line to see all checkboxes
console.log(check_boxes);
});

On clicking the textbox the selectRow checkbox function should not work

. .I need a help. . I have a table row in which there is a checkbox, textbox. and some numbers
On clicking the row the checkbox gets checked and clicking it again the checkbox gets unchecked. But there is a problem, after checkbox is checked when i click on textbox to enter a value the checkbox also gets unchecked.I don't want that to to happen. I need to remove the row select function only for the textbox cell. . please help out guys. . .
js code:
function selectRow(row)
{
var chk = row.getElementsByTagName('input')[0];
if (!chk.disabled) {
chk.checked = !chk.checked;
}
}
fiddle
Just add onclick="event.stopPropagation()" to the textbox :
<td width="30" valign="middle"><input name="Item2_quantity1" type="text"
class="tb5"placeholder="1" id="Item2_quantity1" size="1" maxlength="2" value="1"
onclick="event.stopPropagation()" /></td>
Here's an updated fiddle
As you are using jQuery in fiddle. Try this:
$("table#Item2_listing tr").click(function(e){
if(e.target.type!=="text"){
var chk = $(this).find('input[type=checkbox]')[0];
if (!chk.disabled) {
chk.checked = !chk.checked;
}
}
});
DEMO

Categories

Resources