php javascript change innerHTML with select value from table - javascript

I've got a form with a input field(FIELD1). When the user types in FIELD1 it filters values in FIELD2. Then they click on FIELD2 and it display's the value selected via javascript (this tutorial: http://www.tizag.com/javascriptT/javascript-innerHTML.php). The problem I'm having is that the value of FIELD2 is the companyID in the table - how do I include the javascript to lookup the company name from the table. Picture attached.
<script type="text/javascript">
function changeText2(){
var userInput = document.getElementById('cv_bus').value;
document.getElementById('boldStuff2').innerHTML = userInput;
document.getElementById('filterTxt').innerHTML = userInput;
}
</script>
<table style="width:500px;border:1px solid #000;">
<tr><td>2</td><td>Type in the box below to narrow the list of names:</td></tr>
<tr><td></td><td><input type="text" name="filterTxt" id="filterTxt" tabindex="2" style="width: 400px"></td></tr>
<tr><td></td><td><p>SELECTED: <font color=red><b id='boldStuff2'>NONE</b> </p></font></td></tr>
<tr><td></td><td>Select the apropriate name:</td></tr>
<tr><td></td><td><select autocomplete="off" id="cv_bus" name="cv_bus" size=15 tabindex="2" style="width: 400px" onclick="changeText2()">
<?php
include 'cv_con.php';
$get = mysqli_query($con,"SELECT * FROM cv_companies order by compname");
$result = mysqli_query($con,"SELECT * FROM cv_companies order by compname");
//$option = '';
while($row = mysqli_fetch_array($result)) {
$option .= '<option value = "'.$row['id'].'">'.$row['compname'].'</option>';
}
?>
<?php echo $option; ?></select>

var el = document.getElementById('cv_bus');
var text = el.options[el.selectedIndex].innerHTML;
Try this example, first get the ID then access to the options label.

replace this
var userInput = document.getElementById('cv_bus').value;
with
var userInput = cv_bus.options[cv_bus.selectedIndex].text;
another way is pass this in function:
<select autocomplete="off" id="cv_bus" name="cv_bus" size=15 tabindex="2" style="width: 400px" onclick="changeText2(this);">
function changeText2(selObj){
var userInput = selObj.options[selObj.selectedIndex].text;
document.getElementById('boldStuff2').innerHTML = userInput;
document.getElementById('filterTxt').innerHTML = userInput;
}

Related

Value from textbox gets blank after update

I have this edit link (name) where the value from the database gets transformed to textbox when clicked. The problem is when I update other normal textbox (age), the value from the edit link textbox becomes blank. But when I input a value into the edit link textbox, the value is saved. Why is it that everytime I update other textbox, the edit link textbox value becomes blank? Please help
$(document).ready(function() {
$('a.edit').click(function (e) {
e.preventDefault();
var dad = $(this).parent().parent();
dad.find('label').hide();
dad.find('input[type="text"]').show().focus();
return false;
});
$(".edit-input").focusout(function() {
var dad = $(this).parent();
$(this).hide();
dad.find('label').show();
});
$sql = "SELECT * FROM details";
$result = mysqli_query($conn,$sql);
while ($rowwaf = mysqli_fetch_assoc($result)) {
echo "<td><label for=\ "name\" class=\ "control-label\">
<p class=\"text-info\" style=\"color: black\">".$rowwaf["name"]."</p></label>
<input type=\ "text\" class=\ "edit-input\" name=\ "name\" placeholder=\ " ".$rowwaf[ "name"]. " \" maxlength=\ "10\" />
<div class=\ "controls\">
<a class=\ "edit\" href=\ "#\">Edit</a>
</div>
echo "<td ><input size=\"18\" type=\"text\" name=\"age\" value=\"".$rowwaf["age"]."\"></td>\n" ;
</td>";
My update query:
$name = $_POST["name"];
$age = $_POST["age"];
$id = $_POST["id"];
$updquery = "UPDATE details
SET name = '$name', age = '$age'
WHERE id = '$id'";
$result = mysqli_query($conn,$updquery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I guess the problem is with the echo statement from php.
<input type="text" class="edit-input" name="name" placeholder="$rowwaf["name"]" value="$rowwaf["name"]" maxlength="10" />
You are setting placeholder, I guess you also need to set the value attribute to the input tag.
If it doesn't help, try including a running snippet. Maybe we could do something about it then!

How to insert values of dynamic fields into database using PHP ,MySqL and JQuery

I am trying to make a country -state selector in Jquery which should submit values in db using PHP. Here is the script:
<script type="text/javascript">
var state_arr=new Array("Jammu and Kashmir","Delhi","Uttar Pradesh","Tamil nadu","Maharashtra","Karnataka","West Bengal","Punjab","Haryana");
var s_a = new Array();
s_a[0]="";
s_a[1]="Srinagar|Jammu";
s_a[2]="New Delhi";
s_a[3]="Lucknow|Kanpur|Ghaziabad|Noida|Varanasi";
s_a[4]="Chennai";
s_a[5]="Mumbai|Pune|Aurangabad|Thane";
s_a[6]="Bangalore|Mysore";
s_a[7]="Kolkata";
s_a[8]="Chandigarh|Mohali";
s_a[9]="Gurgaon|Chandigarh";
function print_state(state){
//given the id of the <select> tag as function argument, it inserts <option> tags
var option_str = document.getElementById(state);
option_str.length=0;
option_str.options[0] = new Option('Select State','');
option_str.selectedIndex = 0;
for (var i=0; i<state_arr.length; i++) {
option_str.options[option_str.length] = new Option(state_arr[i],state_arr[i]);
}
}
function print_city(city, selectedIndex){
var option_str = document.getElementById(city);
option_str.length=0;
option_str.options[0] = new Option('Select City','');
option_str.selectedIndex = 0;
var city_arr = s_a[selectedIndex].split("|");
for (var i=0; i<city_arr.length; i++) {
option_str.options[option_str.length] = new Option(city_arr[i],city_arr[i]);
}
}
Here is the PHP code which displays the selector:
<?php if (!isset($_POST['submit_val3'])) { ?>
Select the State:
<select onchange="print_city('city',this.selectedIndex);" id="state" name ="state"></select>
<br />
City:
<select name ="city" id ="city"></select>
<script language="javascript">print_state("state");</script>
<input type="submit" name="submit_val3" value="Submit" />
<?php } ?>
Here is PHP code for submission:
if(isset($_POST['submit_val3']))
{
$city=$_POST['city'];
$state=$_POST['state'];
$dbc = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die(mysql_error());
mysql_select_db(DB_NAME);
$query="UPDATE register_emp SET state='$state',city='$city' WHERE ID = '" . $_SESSION['ID'] . "'";
mysql_query($query,$dbc) or die('query failed');
mysql_close();
}
My problem is that on clicking on Submit button,no values are being submitted to database.Where am I wrong here ?
Please add a form tag and action , thats why its not submitting to php page.
<?php if (!isset($_POST['submit_val3'])) { ?>
<form method="post" action="yourphppage.php"> <!-- form tag and action page -->
Select the State:
<select onchange="print_city('city',this.selectedIndex);" id="state" name ="state">
City:
<select name ="city" id ="city">
<script language="javascript">print_state("state");
<input type="submit" name="submit_val3" value="Submit" />
</form>
<?php } ?>

get radio button value (PhP MySQL and ajax)

Newbie here..
I have this code for my displaying the database records in a table,
I want to know how do i get the value of radio button (the radio button contains the id of selected row). I tried doing it in javascript but no luck.
table.php
<table border="1">
<th></th>
<th>Particulars</th>
<th>Amount</th>
<?php
include('includes/config.php');
$qry = $con->prepare('SELECT * FROM fees');
$qry->execute();
$row = $qry->rowCount();
while ($row = $qry->fetch(PDO::FETCH_ASSOC)) {
$id = $row['fee_id'];
$fee = $row['fee_name'];
$amt = $row['amount'];
?>
<?php echo "
<tr title='Click to edit or delete record'>
<td><input type = 'radio' name = 'radio' class ='radio' value = $row[fee_id]></td>
<td>$fee</td>
<td>$amt</td>
</tr>
"; ?>
<?php } ?>
</table>
<input type="button" value="Delete Selected Fee" style="width:250px; height:40px;font-weight:bold;" onclick="delete();"><br><br>
javascript code
<script type="text/javascript">
function delete(){
if (document.getElementsByClassName(this.class).checked){
var val = document.getElementsByClassName(this.class).value;
alert (val);
}
}
</script>
Use this
function delete(){
if($('input[name="radio"]').is(':checked')){
var val = $('input[name="radio"]').val();
console.log(val);
}
}
I suggest you to use hidden field instead if you don't want to show. The property of radio buttons is to show only true / false value. It may be on / off or yes / no, according to your uses. Use like
<input type = 'hidden' name = 'whatever' class ='radio' value =<?php echo $row['fee_id']; ?>>
You can try this, this should get your radio button value using your input name.
<script type="text/javascript">
function delete(){
if($('input[name="radio"]').is(':checked')){
var val = $('input[name="radio"]').val();
alert (val);
}
}
</script>
Following code will give you your radio button value
<script type="text/javascript">
function delete(){
if($('input[name="radio"]').is(':checked')){
var val = $('input[name="radio"]').val();
alert (val);
}
}
</script>
you can use console.log(val);

Posting JavaScript Variable to MySQL using PHP

I am trying to send a JavaScript variable to PHP but not exactly sure how to do it, a few things have said Ajax but I've never used it before and can't get my head around it. Does anyone know what the easiest way to do this would be? The column which I am attempting to populate in my DB is called 'cogs'.
I have the following JavaScript code:
<script>
$(document).ready(function() {
$('#duration-select').change(function() {
var cogs = $('#cogsday').html();
cogs = cogs.replace(/\D/g,'');
var x =$('#duration-select').val();
var y = cogs * x;
$('#request').removeClass('hidden');
$('#duration-value').text('Total cost for this duration = ' + (y) + ' cogs');
if($(this).val() !== '') {
} else {
$('#duration-value').text('');
}
});
$('#request').click(function() {
var cogs = $('#cogsday').html();
cogs = cogs.replace(/\D/g,'');
var x =$('#duration-select').val();
var y = cogs * x;
$('#total').text(y);
});
});
</script>
And the following HTML code:
<label id="total"></label>
Here is where I am trying to post the data, everything else is posting except for the $cost:
<form name="form" method="post">
<div class="modal-footer">
<?php
if ($row3['availability'] === 'Available') {
if (isset($_POST['request'])) {
$to_id = $row3['customerid'];
$from_id = $_SESSION['customerid'];
$time_sent = date('Y-m-d H:i:s');
$subject = 'Request for ' . $row3['title'];
$title = $row3['title'];
$listingid = $listingid;
$cost = $_POST['total']; //posting 0
$message = $customer_data['first_name'] . ' ' . $customer_data['last_name']
$request = mysql_query("INSERT INTO messages (to_id, from_id, listing_id, time_sent, subject, message, cogs, messagenumber, title, msgrand) VALUES ('$to_id', '$from_id', '$listingid', '$time_sent', '$subject', '$message', '$cost', '1', '$title', '$randomString')") or die(mysql_error());
}
}
?>
<input type="submit" class="btn btn-success" name="request" value="Yes" />
<input type="submit" class="btn btn-danger" data-dismiss="modal" value="No" />
</div>
</form>
Then I am trying to post the value of the label id=total to my db or the JavaScript variable (y). The problem is that 0 is always being sent to the DB when it should instead be the value that is in the label where the id is total.
Use name parameter for hidden variable and it will be automatically passed to PHP .
<label id="total"></label>
<input type="hidden" name="total" id="nameID"/>
in javascript below $('#total').text(y); write $('#nameID').val(y); . Everything will work properly.
You used total label , but $_POST recognizes only input type so use input type=.... instead of a label,divs etc.
IF YOU REAllY NEED ANSWER REPLY HERE
you have make an input type and its value is to be set by that javascript and then you'll be able to get that $cost value in php code
<input type="hidden" value="" name="total" id="total">
..................
$("#total").val(y);
You can use this to send the variables....
<input type="text" id="name" class="name" placevalue="Enter you name" required /><br><br>
<input type="text" id="email" class="email" placevalue="Enter you name" required /><br><br>
<button id= "det_submit" onclick="submit_det()"> Submit </button>
<script>
function submit_det() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
if(name != "" && email != "") {
$.post(
'xx.php',
{
name : document.getElementById("name").value,
email1 : document.getElementById("email").value,
},
function(data){
alert(data);
});
} else {
alert("empty");
}
}
</script>
here is xx.php
<?php
if(isset($_POST['name']) && isset($_POST['email1'])) {
$name = $_POST['name'];
$email = $_POST['email1'];
//code to insert into your database......
}
?>
Use a ID and Name for hidden parameter like this
<label id="total"></label
<input type="hidden" name="name" id="name"/>
and in jQuery edit the code like this
$('#total').text(y);
$('#nameID').val(y);
hope that it will work

how to fetch values from array input in javascript

How do I properly fetch values from array in javascript:
<html>
<head>
<script type="text/javascript">
function proc()
{
var cost = document.yoh.coz.value;
var qtybuy = document.yoh.qbuys.value;
var st = cost * qtybuy;
var tbox = document.yoh.subtotal;
if (tbox)
{
tbox.value = st;
}
}
</script>
</head>
<body>
<?php
include('conn.php');
$prodname = $_GET['prodname'];
$result = query_database("SELECT * FROM prod_table WHERE PRODUCT='$prodname'", "onstor", $link);
?>
<?php while ( $row = mysql_fetch_array($result) ) { ?>
<form name="yoh" method="get">
Product id: <input type="text" name="prodid" value=""><br/>
Cost: <input type="text" name="coz" value="<?php echo $row['S_PRICE']; ?>"><br/>
Quantity to buy:<input type="text" name="qbuys" value="" onkeyup="proc();"></br>
Subtotal:<input type="text" name="subtotal" value=""></br>
</form>
</body>
<?php } ?>
</html>
As you can see this program will just multiply the 2 values. One of the values would be fetched from the database, and the other comes from the user.
If I do it this way, I don't get any results:
<html>
<head>
<script type="text/javascript">
function proc()
{
var cost = document.yoh.coz[].value;
var qtybuy = document.yoh.qbuys[].value;
var st = cost * qtybuy;
var tbox = document.yoh.subtotal[];
if (tbox)
{
tbox.value = st;
}
}
</script>
</head>
<body>
<?php
include('conn.php');
$prodname = $_GET['prodname'];
$result = query_database("SELECT * FROM prod_table WHERE PRODUCT='$prodname'", "onstor", $link);
?>
<?php while ( $row = mysql_fetch_array($result) ) { ?>
<form name="yoh" method="get">
Product id: <input type="text" name="prodid[]" value=""><br/>
Cost: <input type="text" name="coz[]" value="<?php echo $row['S_PRICE']; ?>"><br/>
Quantity to buy:<input type="text" name="qbuys[]" value="" onkeyup="proc();"></br>
Subtotal:<input type="text" name="subtotal[]" value=""></br>
</form>
</body>
<?php } ?>
</html>
Do I need to include the index manually? What do I need to do to achieve the same results when using arrays.
You can use a name value:
cost=document.yoh.elements['coz[]'].value;
You need to iterate through the arrays. To iterate through an array (or object) in JavaScript:
for (key in arr){
// The key will be set to each key in the array (arr)
// The value at that key will be arr[key] (like always)
}
I'm not entirely sure what your goal is, but in general, know that the "[]" syntax is PHP only, JavaScript treats it as any other name (and possibly as a syntax error).

Categories

Resources