Get form dropdown value before POST? - javascript

I have a page with 2 forms. The first form (below) is just a drop down list of values which controls what is loaded into the 2nd form. The 1st form submits to the same page.
Without making the 1st form (on submit) open a 2nd page with the 2nd form, is there a way (on load) to get the currently selected value of the drop down for use in the second form? This is only a problem on the initial page load. Thanks.
<form action="/get_gs_link_status.php" method="post" onchange="submitForm()">
<select name="select_PM" id="select_PM">
<?php
while ($row = $result->fetch_assoc()) {
echo "<option value=\"{$row['PM']}\">";
echo $row['PM'];
echo "</option>";
}
?>
</select>
</form>
<p id="PID_value"></p>
<script>
function submitForm() {
var x = document.getElementById("select_PM").value;
document.getElementById("PID_value").innerHTML = "You selected: " + x;
}
</script>

Add an onload handler that calls submitForm().
<p id="PID_value"></p>
<script>
function submitForm() {
var x = document.getElementById("select_PM").value;
document.getElementById("PID_value").innerHTML = "You selected: " + x;
}
window.addEventListener("load", submitForm);
</script>

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>

Javascript generated select not posting in PHP

I have searched far and wide and have not seen an answer for this. Forgive me if one exists.
I have a PHP page, in which user can generate new html select fields by pressing a button. I use Javascript to generate the new select fields. The user can then select one option from the generated select field. I need the value the user chose in PHP code below the form, to submit the form values to database.
My problem is that PHP doesn't seem to recognize the new generated select fields, which is why it won't post.
var_dump($_POST) doesn't show the new select field. I have also tried to name the new select as name="choice1[]", but that also has not posted. Choice1 is always undefined.
All of my code is on the same PHP page, apart from sql query to populate the select options.
This is what Javascript generates inside a form:
<select class="form-control" id="choose1" name="choice1">
<option value="1:x">Text</option>
<option value="2:y">Text</option>
<option value="3:z">Text</option>
</select>
This is where I try to get the value, after submit button is pressed:
if (isset($_POST['choice1'])){
$choice1 = $_POST['choice1'];
$parts1 = $choice1;
$arr1 = explode(':', $parts1);
$tNum = $arr1[0];
$tName = $arr1[1];
}
The Javascript works fine, the values are shown on the page fine. The only part not working is the post method (well, only for this specific select field. Other's work fine, as those are hard coded to html). Submit button works fine, everything else gets submitted.
My question is if there is a way for me to get the post values in PHP without reloading the page?
Or if reload is needed, how to do this without closing the form modal?
Or even more of a general question would be.. How do I do this?
EDIT:
Here is my form code. I deleted bunch of other stuff from it just to show the parts I have the problem with. If the divs are weird, it's because of that.
<form class="form-horizontal" method="post" action="">
<div class="modal-header">
<h4 class="modal-title">Change</h4>
</div>
<div class='modal-body'>
<div class='row'>
<label class="col-sm-3"> Product: </label>
<div class="col-sm-8" id="selectProd">
<!-- **This is where new select is generated** -->
<select class='form-control' id='valinta' name='choice'>
<?php
$sql0= "SELECT tuotenro, tuotenimi FROM vaateHenkilot WHERE asnro = '". $_GET['b']."' AND henknro = '". $_GET['a']."' GROUP BY tuotenro, tuotenimi";
$req = sqlsrv_query($con, $sql0) or die(print_r(sqlsrv_errors(),true));
$t = '';
while($row = sqlsrv_fetch_array($req)) {
$t = array(
array (
'nro' => $row['tuotenro'],
'nimi' => $row['tuotenimi'],
)
);
$tuotteetIN = array_column($t, 'nimi', 'nro');
foreach($tuotteetIN as $key => $value) {
?>
<option value="<?php echo $key ?>:<?php echo $value ?>"><?php echo $value ?></option>
<?php
}
}
?>
</select>
<br>
</div>
<div class="col-sm-1">
<button type='button' class='btn' onclick='addSelectBox()'>+</button>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success" name="saveButton">Save</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</form>
<?php
if (isset($_POST['saveButton'])) {
$choice = $_POST["choice"];
$parts = $choice;
$arr = explode(':', $parts);
$tNum = $arr[0];
$tName = $arr[1];
if (isset($_POST['choice1'])){
$choice1 = $_POST['choice1'];
$parts1 = $choice1;
$arr1 = explode(':', $parts1);
$tNum = $arr[0] . ', ' . $arr1[0];
$tName = $arr[1] . ', ' . $arr1[1];
}
*Here is the sql query*
}
?>
I have another select there, which has the same values. That one works well.
I'll add the Javascript here that creates the new select, as well.
<script type="text/javascript">
var j = 0;
function addSelectBox (){
if (j < 3){
var parentDiv = document.getElementById ("selectProd");
var selectElement = document.createElement ("select");
j++;
selectElement.setAttribute("class", "form-control");
selectElement.setAttribute("id", "choose" + j);
selectElement.setAttribute("name", "choice" + j);
var tuotteet = '';
$.ajax({
type: 'GET',
url: 'productHelp.php?asi=<?php echo $asnro; ?>&hen=<?php echo $henro; ?>',
data: tuotteet,
datatype: 'json',
cache: false,
success: function (data) {
var tnimi = data.split(";");
for (var i=0;i < tnimi.length -1;i++){
var tnro = tnimi[i].split(",");
var option = new Option (tnro[1], tnro[0]+":"+tnro[1]);
selectElement.options[selectElement.options.length] = option;
}
}
});
parentDiv.appendChild (selectElement);
parentDiv.appendChild(linebreak);
}
}
</script>
Turns out the problem was as "stupid" and simple as I figured it had to be.
Taking the modals with the functionality out from the table structure made it work fine.
Good to learn something new about formatting everyday!

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

Show and hide element through different tabs PHP

I have a select inside a form with different types of devices from the database (devices.insert.php):
Type:<select name="type" form="form_select" onchange="showDiv(this)">
<?php
$sql = "SELECT *
FROM Property
WHERE PRP_PRP_TYP_Id = 1";
$result = sqlsrv_query($con, $sql);
echo "<option disabled selected value> -- select an option -- </option>";
while ($row = sqlsrv_fetch_array($result)){
echo "<option value='".$row['PRP_Id']."'>".$row['PRP_Value']."</option>";
}
?>
</select><br>
<script type="text/javascript">
function showDiv(elem){
if(elem.value == 3 || elem.value == 24 || elem.value == 25){
document.getElementById('sc_div').style.display = "block";
}
else{
document.getElementById('sc_div').style.display = "none";
}
}
</script>
And when I select one of the items with the correct id, a div element turns visible with more options.
<div id="sc_div" style="display:none">
...
Register new SIM<br>
</div>
In sim_cards_insert.php I have a form with submit and cancel and when I press to go back (to devices_insert.php) the div sc_div is not visible again but the data that I've filled before is in the same place.
<button type="button" class="log-btn" onClick="history.go(-1)">Cancel</button>
How can I get it visible again passing through different windows?
Sounds like the browser is reverting the DOM to it's initial state - ie with the sc_div hidden.
Perhaps you could check the previous URL for the devices_insert.php page load.
<script type="text/javascript">
function showDiv(elem){
//example
var filename = document.referrer.split('/').pop();
if(filename === 'sim_card_insert.php'){
document.getElementById('sc_div').style.display = "block";
}
//...rest of function
</script>

Duplicate form submition through $("#formname").submit();

I have a line of HTML drop down lists, and whenever the user selects one of the options, it calls a jQuery function through a class which submits the form.
<form id="workorderform" action="saveworkorder.php" method="post">
<select name="applicationtype" class="checkvalueonchange savevalueonchange">
<option></option>
<option value="Uplift" <?php echo ($wo['applicationtype']=='Uplift')?'selected':''; ?>>Uplift</option>
</select>
</form>
the savevalueonchange class calls
$(".savevalueonchange").change(function() {
autoSave();
});
which then calls
function autoSave() {
if($("#wostatus").val()=='open'){
$("#workorderform").submit();
}
}
which posts the information to the saveworkorder.php
//remove existing chargecodes
$sql = "DELETE FROM workorderchargecodes WHERE compresscoid = '".trim($_REQUEST['formid'])."'";
mssql_query($sql, $dbconn);
//now save chargecodes
$code_prefix = 'code_';
foreach($_POST as $thisPostKey => $thisPostValue) {
if((substr($thisPostKey, 0, strlen($code_prefix)))==$code_prefix) {
if(trim($thisPostValue)!=''):
$exists=false;
$sql = "SELECT * FROM workorderchargecodes WHERE compresscoid='".trim($_REQUEST['formid'])."' AND code='".substr($thisPostKey, strlen($code_prefix), strlen($thisPostKey))."'";
$res = mssql_query($sql, $dbconn);
while($arr = mssql_fetch_assoc($res)){
$exists=true;
}
if($exists==false){
$sql = "INSERT INTO workorderchargecodes (
compresscoid,
code,
time
) VALUES (
'".trim($_REQUEST['formid'])."',
'".substr($thisPostKey, strlen($code_prefix), strlen($thisPostKey))."', '".$thisPostValue."'
)";
mssql_query($sql, $dbconn);
}
endif;
}
}
As you can see, I am selecting the code from the database before I insert it into the database and am somehow still getting duplicate charge codes. I have messed with this for a few months now, and it still keeps happening.
Any ideas?
Try to add return false; in your autosave(), like this :
function autoSave() {
if($("#wostatus").val()=='open'){
$("#workorderform").submit();
return false; // add here
}
}
It will prevent to submit twice.
<form id="workorderform" action="saveworkorder.php" method="post" onsubmit="return false;">
<select name="applicationtype" class="checkvalueonchange savevalueonchange">
<option></option>
<option value="Uplift" <?php echo ($wo['applicationtype']=='Uplift')?'selected':''; ?>>Uplift</option>
</select>
</form>
use this form
it use obsubmit="return false;"

Categories

Resources