php - if radio button selected, select value from table of database - javascript

I'm using codeigniter and i have some issue with radio button, javascript, and php.
The radio button is used for selecting type of customer. This is my radio button on view file
<input type="radio" name="customerType" value="Reseller" /> Reseller
<input type="radio" name="customerType" value="Dropshipper" /> Dropshipper
<input type="text" class="form-control" value ="" name="customerCode" aria-describedby="basic-addon1" />
When Reseller radio button selected, I want the value of customerCode will showing codename like "RSL", and when Dropshipper selected, the value of customerCode showing "DRP" automatically.
Please advice,
Thank you very much :)
============================AFTER SOLVED============================
Hi guys, after this case was solved i want to share my code.
as we know, this thread will auto generating value of form input depends by radio button. And we got it! Thanks to Ashwani Goyal :)
And now, I want to give a numerical character on this form input. So this is my model code :
function getCustomerCodeRSL(){ //this function will generating when "RSL" radio button selected
$q = $this->db->query("select MAX(RIGHT(customer_code,3)) as codeMax from customer where customer_code like 'RSL%'");
$code = "";
if($q->num_rows()>0){
foreach($q->result() as $k){
$tmp = ((int)$k->codeMax)+1;
$code = sprintf("%03s", $tmp);
}
}else{
$code = "001";
}
return $code;
}
function getCustomerCodeDRP(){ //this function will generating when "DRP" radio button selected
$q = $this->db->query("select MAX(RIGHT(customer_code,3)) as codeMax from customer where customer_code like 'DRP%'");
$code = "";
if($q->num_rows()>0){
foreach($q->result() as $k){
$tmp = ((int)$k->codeMax)+1;
$code = sprintf("%03s", $tmp);
}
}else{
$code = "001";
}
return $code;
}
And this is my controller :
function cCustomer(){
$data = array(
'data_customer' => $this->Model_App->getAllData('customer'),
'total_customer' => $this->Model_App->counterAllRowTable('customer'),
'cust_codeRSL' => $this->Model_App->getCustomerCodeRSL(),
'cust_codeDRP' => $this->Model_App->getCustomerCodeDRP(),
);
$this->load->view('admin/header');
$this->load->view('admin/vCustomer', $data);
$this->load->view('admin/footer');
}
So, the output will be like this :
if DRP selected then the output is; DRP001, DRP002, ... and more
if RSL selected then the output is; RSL001, RSL002, ... and more.
hope it will helping someone else out there who need the same thing with me :)

Try the following:
$("input[name='customerType']").click(function(){
$("input[name='customerCode']").val( $(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="customerType" value="RSL" id="rsl" /><label for="rsl">Reseller</label>
<input type="radio" name="customerType" value="DSL" id="dsl"/> <label for="dsl">Dropshipper</label>
<input type="text" class="form-control" value ="" name="customerCode" aria-describedby="basic-addon1" />

i think thats it you want fiddle
<input type="radio" name="customerType" value="RSL" /> Reseller
<input type="radio" name="customerType" value="DSL" /> Dropshipper
<input type="text" class="form-control" value ="" name="customerCode" aria-describedby="basic-addon1" /
$("input[name='customerType']").click(function(){
$("input[name='customerCode']").val( $(this).val());
});

if($_POST['customerType'] == "Reseller"){
$_POST['customerCode'] = "RSL";
}elseif($_POST['customerType'] == "Dropshipper"){
$_POST['customerCode'] = "DRP";
}
Easiest way with only php

Related

Get a value from a PHP Page to a Javascript in Another Page Issue

this time i am having a problem to get a value of a php file where the goal is make a query (that part is done), validate if the query doesn't work, return false or else true.
That file is called into a javascript var to get the true/false value, but it doesn't work. I know that i'm failing because i printed the boolean value and alert shows "[object][object]".
Here is my HTML file
<form class="form-inline" id="formpqrs1" onSubmit="Validate()" method="get">
<label> <h4><b>Information</b></h4></label>
<br>
<select id="s2" name="s2" style="min-width:25%"></select>
<br><br>
<label><h4><b>Insert Element Name</b></h4></label>
<br>
<input name="Nombre" id="Lugarpqrs" type="text" class="form-control" placeholder="NOMBRE" required>
<br> <br>
<div id="motivos">
<label> <h4><b>Choose Type:</b></h4></label>
<br>
<div class=radio-inline>
<label>
<input type="radio" name="tipomotivo" id="tipomotivo" value="1"><h5>Type 1</h5>
</label>
</div>
<div class=radio-inline>
<label>
<input type="radio" name="tipomotivo" id="tipomotivo" value="2"><h5>Type 2</h5>
</label>
</div>
<div class=radio-inline>
<label>
<input type="radio" name="tipomotivo" id="tipomotivo" value="3"><h5>Type 3</h5>
</label>
</div>
<div class=radio-inline>
<label>
<input type="radio" name="tipomotivo" id="tipomotivo" value="4"><h5>Type 4</h5>
</label>
</div>
<br><br>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
Here my Javascript file where i get the value of the php file, i validate from a radio button, then i create a var to get the value of the php file where the query is done.
function Validate(){
if($("#opcion:checked").val() === "1"){
var validar = false;
var validar = $.get("validaciones/Validar_Ubicacion.php?lugar="+$("#Lugarpqrs").val()+"");
if(!validar){
$.get("php/Ingresar_tipo.php?lugar="+$("#Lugarpqrs").val()+"");
alert("Success" + validar);
}
else{
alert("Element Already Exist in DB" + validar);
}
}
Here is my php file
<?php
$lugar=$_GET["lugar"];
$conexion = mysqli_connect($server, $user, $pass,$bd)
or die("ERROR");
$confirmacion = false;
$sql = "SELECT * FROM `lugar` WHERE `nombre` = '".$lugar."'";
mysqli_set_charset($conexion, "utf8");
if(!$result = mysqli_query($conexion, $sql)) die();
$close = mysqli_close($conexion)
or die("ERROR");
if(!$sql){
echo $confirmacion;
}
else{
$confirmacion = true;
echo $confirmacion;
}
?>
The last part if/else is where i validate if query fails that means the element doesn't exist then return $confirmacion value which is false or else $confirmacion = true which means element already exist and show an alert message in the script that is on another page.
Previously i tested other validations like the query and if/else validations of the radio button (first if validation) and it works, so, the problem is in my var validar, maybe i'm doing wrong when i get the value from my php file.
As always, thanks for your time and attention, all answers are welcome to me.
Good day.
You need to update your logic inside the jquery's .get function (since it's asynchronous.
Update your PHP file to output string "true" and "false" (best practice is to use JSON format & header) - this may work for you.
I updated for you your Javascript file:
function Validate(){
if($("#opcion:checked").val() === "1"){
var validar = false;
$.get("validaciones/Validar_Ubicacion.php?lugar="+$("#Lugarpqrs").val()+"",
function(data){
if(data=="true"){
$.get("php/Ingresar_tipo.php?lugar="+$("#Lugarpqrs").val()+"");
alert("Success" + validar);
}
else{
alert("Element Already Exist in DB" + validar);
}
});
}

Keep input value after refresh page

I have a form with input field and this input contain a drop down menu read information from database.
If the user enters value and when he arrives to the drop menu he doesn't find what he wants he go to another page to add this info to the drop down menu and then go to the first page to continue enter the information.
How can I keep this information if he goes to another page to add info to drop menu and how can after adding the info to drop menu find this info without refresh and without submit.
This is the first page with the form
<form name='' method='post' action='<?php $_PHP_SELF ?>'>
<input name='txt_name' id='' type='text'>
This drop menu read from database
<select id="groups" name="txt_label" class="form-control">
';?>
<?php
$sql=mysqli_query($conn,"select DISTINCT db_label from tbl_label")or die(mysqli_error($conn));
echo'<option value="">-- Select --</option>';
while($row=mysqli_fetch_array($sql)){
$label=$row['db_label'];
echo "<option value='$label'>$label</option>";
}echo'</select>';?><?php echo'
</div>
</form>
Second form in another page
<form class="form-inline" role="form" name="form" method="post" action="';?><?php $_PHP_SELF ?><?php echo'">
<div class="form-group">
<label for="pwd">Label</label>
<input id="txt_label" name="txt_label" type="text" placeholder="Label" class="form-control input-md">
</div>
<div class="form-group">
<label for="pwd">Sub Label</label>
<input id="txt_sublabel" name="txt_sublabel" type="text" placeholder="SubLabel" class="form-control input-md">
</div>
<input type="submit" name="addlabel" value="Add" class="btn btn-default">';
EDIT: Keep value of more inputs
HTML:
<input type="text" id="txt_1" onkeyup='saveValue(this);'/>
<input type="text" id="txt_2" onkeyup='saveValue(this);'/>
Javascript:
<script type="text/javascript">
document.getElementById("txt_1").value = getSavedValue("txt_1"); // set the value to this input
document.getElementById("txt_2").value = getSavedValue("txt_2"); // set the value to this input
/* Here you can add more inputs to set value. if it's saved */
//Save the value function - save it to localStorage as (ID, VALUE)
function saveValue(e){
var id = e.id; // get the sender's id to save it .
var val = e.value; // get the value.
localStorage.setItem(id, val);// Every time user writing something, the localStorage's value will override .
}
//get the saved value function - return the value of "v" from localStorage.
function getSavedValue (v){
if (!localStorage.getItem(v)) {
return "";// You can change this to your defualt value.
}
return localStorage.getItem(v);
}
</script>
if the above code did not work try this:
<input type="text" id="txt_1" onchange='saveValue(this);'/>
<input type="text" id="txt_2" onchange='saveValue(this);'/>
You can also use useContext() from react context() if you're using hooks.
In MVC/Razor,
first you should add a variable in your model class for
the textBox like this:
namespace MVCStepByStep.Models
{
public class CustomerClass
{
public string CustomerName { get; set; }
}
}
Then in Views --> Index.cshtml file make sure the Textbox
is created like this:
#Html.TextBoxFor(m => m.CustomerName)
For a complete example, please check out this site:
How to update a C# MVC TextBox By Clicking a Button using JQuery – C# MVC Step By STep[^]

Using Json how can I select a radio button based on value in my database?

Hi I have a form that has a button used to prefill my form with data from my database. Using Json It works fine to populate text inputs but how do I get it to select a radio button based on the value returned from my database?
FORM
<form action="#">
<select id="dropdown-select" name="dropdown-select">
<option value="">-- Select One --</option>
</select>
<button id="submit-id">Prefill Form</button>
<input id="txt1" name="txt1" type="text">
<input id="txt2" name="txt2" type="text">
<input type="radio" id="q1" name="q1" value="4.99" />
<input type="radio" id="q1" name="q1" value="7.99" />
<button id="submit-form" name="Submit-form" type="submit">Submit</button>
</form>
SCRIPT
<script>
$(function(){
$('#submit-id').on('click', function(e){ // Things to do when
.......
.done(function(data) {
data = JSON.parse(data);
$('#txt1').val(data.txt1);
$('#txt2').val(data.txt2);
$('#q1').val(data.q1);
});
});
});
</script>
/tst/orders2.php
<?php
// Create the connection to the database
$con=mysqli_connect("xxx","xxx","xxx","xxx");
........
while ($row = mysqli_fetch_assoc($result))
{
echo json_encode($row);
die(); // assuming there is just one row
}
}
?>
Don't use ID because you have same ID of both radio buttons
done(function(data) {
data = JSON.parse(data);
$('#txt1').val(data.txt1);
$('#txt2').val(data.txt2);
// Don't use ID because the name of id is same
// $('#q1').val(data.q1);
var $radios = $('input:radio[name=q1]');
if($radios.is(':checked') === false) {
$radios.filter('[value='+data.q1+']').prop('checked', true);
}
});
You currently have both radio buttons using the same ID. ID's should be unique.
You can use the [name] attribute to do this, or you can set a class on the element. Here is an example:
$('input[name=q1][value="'+ data.q1 +'"]').prop('checked', true);
You can do it based on the value of said input:
instead of
$('#q1').val(data.q1);
Try
$('input:radio[value="' + data.q1 + '"]').click();
On a side note, you have both radios with the same ID, the results of an id based selector are going to vary from browser to browser because an id should be UNIQUE
you can refer the following link to solve your problem. works fine for me
JQuery - how to select dropdown item based on value

Returning Error If Radio Button NOT selected - PHP

I've searched through a lot of previously asked questions about php and radio buttons but I haven't yet found something helping in my situation. I'm building a quiz for a server-side scripting class. I'm stuck on the actual quiz part. I want an error message to echo if the user does NOT select an answer to a question. Instead when I hit the submit button without selecting any options, I'm automatically redirected to the results page. How do I correct my code so that the user is given the error message if they hit submit without answering all of the questions? Below is the current code i've written out in an attempt to check the radio buttons and next steps.
<div id="question5"> <!-- each quiz question gets this set up -->
<h2 id="question5_error">WAIT! You did not pick an answer to this question!</h2>
<p>5. What creature pulls the Hogwarts carriages?<br>
<input type="radio" name="creature" value="Cornish Pixies" <?php if (isset($_SESSION["creature"]) && $_SESSION["creature"]="Cornish Pixies"){ echo"checked";} ?> > Cornish Pixies<br> <!-- php code checks to see if radio button has been selected-->
<input type="radio" name="creature" value="Clydesdales" <?php if (isset($_SESSION["creature"]) && $_SESSION["creature"]="Clydesdales"){ echo"checked";} ?> > Clydesdales<br>
<input type="radio" name="creature" value="Hippogriffs" <?php if (isset($_SESSION["creature"]) && $_SESSION["creature"]="Hippogriffs"){ echo"checked";} ?> > Hippogriffs<br>
<input type="radio" name="creature" value="Thestrals" <?php if (isset($_SESSION["creature"]) && $_SESSION["creature"]="Thestrals"){ echo"checked";} ?> > Thestrals<br>
<input type="hidden" name="sent" value="sent" onclick="Project1_Page2.php">
<input type="submit" name="goresults" value="Get Results?">|<input type="reset" name="resetquiz" value="Reset Quiz.">
</form>
</article>
<?php
if(isset($_GET["sent"])){
echo "<script type = 'javascript'>";
if(!isset($_GET["question1"])){ // QUIZ QUESTION 1 CHECK
$_SESSION["author"]=$_GET["author"];
}
else{
echo "document.getElementById('question1').style.backgroundColor = '#ffcccc';
document.getElementById('question1_error').style.display = 'block';";
}
if(!isset($_GET["question2"])){ // QUIZ QUESTION 2 CHECK
$_SESSION["godfather"]=$_GET["godfather"];
}
else{
echo"document.getElementById('question2').style.backgroundColor = '#ffcccc';
document.getElementById('question2_error').style.display = 'block';";
}
if(!isset($_GET["question3"])){ // QUIZ QUESTION 3 CHECK
$_SESSION["prison"]=$_GET["prison"];
}
else
{
echo"document.getElementById('question3').style.backgroundColor = '#ffcccc';
document.getElementById('question3_error').style.display = 'block';";
}
if(!isset($_GET["question4"])){ // QUIZ QUESTION 4 CHECK
$_SESSION["badguy"]=$_GET["badguy"];
}
else
{
echo"document.getElementById('question4').style.backgroundColor = '#ffcccc';
document.getElementById('question4_error').style.display = 'block';";
}
if(!isset($_GET["question5"])){ // QUIZ QUESTION 5 CHECK
$_SESSION["creature"]=$_GET["creature"];
}
else
{
echo"document.getElementById('question5').style.backgroundColor = '#ffcccc';
document.getElementById('question5_error').style.display = 'block';";
}
echo "</script>";
}
?>
Without seeing your HTML, it's hard to tell but here are some suggestions
in your form tag, remove "Action" attribute
<form method="post/get" >
then create a variable
$haserror = false;
and I'm not sure what are you trying to achieve here, but change the code like this
if(!isset($_GET["question1"])){ // QUIZ QUESTION 1 CHECK
$_SESSION["author"]=$_GET["author"];
echo "document.getElementById('question1').style.backgroundColor = '#ffcccc';
document.getElementById('question1_error').style.display = 'block';";
$haserror = true;
}
do the same for all checkboxes
then at the end do your if to show the result page
if(!$haserror)
{
echo '<META http-equiv="refresh" content="0;URL=newpage.php">';
}
however I suggest to rewrite the whole thing, because you are approaching it in a wrong way
First of all if you are using radios you have set their attribute name to one like
<form method="post">
<input name="question" value="1" />
<input name="question" value="2" />
<input name="question" value="3" />
<input name="question" value="4" />
</form>
in this way you set your logic statement like so.
if(isset($_POST['question'])){
//here you put the the right answer based on the user what he/she chose.
}
I suggest you to use POST is secured. If you are using GET the values of radio will appear on the url. I hope this will help.
Peace

Issue with processing form i ajax with radio buttons

I have this script which makes possible the insertion of some data using ajax and php.
Now , all works fine, except the radio buttons (the select options work fine as well) , and it takes the first value of the radio buttons..
Why is this happening?
Here is the code:
<div id="formfields" ><label>Tipologia Pdv: </label>
<input type="radio" name="tipologia_pdv" id="tipologia_pdv" value="Iper" style="width:40px;" /><span > Iper</span>
<input type="radio" name="tipologia_pdv" id="tipologia_pdv"
value="Super" style="width:40px;" /><span > Super</span><br /><br /></div>
<div id="formfields" ><label>Richiesta Ccnl: </label>
<input type="radio" name="richiesta_ccnl" id="richiesta_ccnl" value="Si" style="width:40px;"/><span> Si</span>
<input type="radio" name="richiesta_ccnl" id="richiesta_ccnl"
value="No" style="width:40px;"/><span> No</span><br /><br /></div>
The javascript:
// Fetch data from input fields.
var js_tipologia_pdv = $("#tipologia_pdv").val();
var js_richiesta_ccnl = $("#richiesta_ccnl").val();
//let's put all data together
var myData = 'postTipologia_pdv='+ js_tipologia_pdv + '&postRichiesta_ccnl='+ js_richiesta_ccnl + '&postDistretto_pdv=' + js_distretto_pdv + '&postCoopva_pdv=' + js_coopva_pdv + '&postNome_pdv=' + js_nome_pdv;
In php they go something like this:
$postTipologia_pdv = filter_var($_POST["postTipologia_pdv"], FILTER_SANITIZE_STRING);
$postRichiesta_ccnl = filter_var($_POST["postRichiesta_ccnl"], FILTER_SANITIZE_STRING);
Making my comments into an answer:
1) Your id attributes need to be unique.
2) Get the value of the selected radio button using something like: $('input:radio[name=tipologia_pdv]:checked').val();

Categories