I've been having a problem calling a function declared in an external .js file.
I've made an include of the .js file in the main page, but apparently it works in part (Just one function it is called correctly, the others generate an "Uncaught ReferenceError: function is not defined ")
Here's the Js file:`
<script type="text/javascript">
var maxAmount = 170;
// Modify the counter textField by given the textField to control and his counter
function textCounter(id_Tf, id_Cd) {
// Method that is called succesfully
var element = document.getElementById(id_Tf);
var nameLenght = element.value.length;
var countDisplay = document.getElementById(id_Cd);
if(nameLenght <= maxAmount){
countDisplay.value = maxAmount - nameLenght;
}
else{
countDisplay.value = "0";
}
function titleShow(){
theTitle = val('title').replace(/^\s+|\s+$/g,"");
get('out_title').innerHTML = theTitle;
if(get('check_bold').checked == true){
highlightTerms('out_title');
}
}
function snippetShow(){
console.log("I've entered here");
theSnippet = val('description').replace(/^\s+|\s+$/g,"");
if(theSnippet.length + dateLength <= 156){
get('out_snippet').innerHTML = theSnippet;}
else{
var snipLimit = 153 - dateLength;
snippetSpace = theSnippet.lastIndexOf(" ",snipLimit);
get('out_snippet').innerHTML = theSnippet.substring(0,snippetSpace).concat(ellipsis.bold());}
}
function urlFunction(){
var theURL = val('in_url');
theURL = theURL.replace('http://','');
theURL = theURL.replace(/^\s+|\s+$/g,"");
get('out_url').innerHTML = theURL;
if(get('check_bold').checked == true){
highlightURL();}}
And here's the Main page: '
<?php
include('Code/Php_code.php');
include('Code/Js_code.js');
?>
<!DOCTYPE html>
<html>
<head>
<title><?php echo $title ?></title>
</head>
<body>
<form action="Database_Interface.php" method="post"><br>
Title:<br>
<input type="text" id="title" name="title" size="150" maxlength="150" value="<?php echo $title ?>" onKeyUp='textCounter("title","countDisplay");'><br>
<input readonly type="text" id="countDisplay" size="3" maxlength="3" value="150"> Characters Remaining
<br><br>
Description:<br>
<input type="text" id="description" name="description" size="150" value="<?php echo $tags['description'] ?>" onKeyUp='textCounter("description","countDisplay2");'><br>
<input readonly type="text" id="countDisplay2" size="3" maxlength="3" value="150"> Characters Remaining
<br><br>
Keywords:<br>
<input type="text" id="keywords" name="keywords" size="150" value="<?php echo $tags['keywords'] ?>" onKeyUp='textCounter("keywords","countDisplay3");'><br>
<input readonly type="text" id="countDisplay3" size="3" maxlength="3" value="150"> Characters Remaining
<br><br>
<input type="submit" value="Carica sul database">
<input type="button" value="see" onclick='snippetShow();'>
</form><br>
<div style="background-color:#f2f2f2; border:1px solid; border-color: black; position:relative;">
<h3><span id="out_title"></span></h3>
<div>
<cite><span id="out_url" ><?php echo $site ?></span></cite>
</div>
<div>
<span id="out_snippet">sdsdsdfvbfbf</span>
</div>
</div>
The answer is: why just the first method is called successfully while the other two generate an error?
Your first function seems to lack a closing } bracket. The last bracket is from the else block. Fixed:
function textCounter(id_Tf, id_Cd) {
// Method that is called succesfully
var element = document.getElementById(id_Tf);
var nameLenght = element.value.length;
var countDisplay = document.getElementById(id_Cd);
if(nameLenght <= maxAmount) {
countDisplay.value = maxAmount - nameLenght;
}
else {
countDisplay.value = "0";
}
}
First of all close <script> tage at end of your js.php file byv </script>
Do not include js file before <doctype> tag.
include it in <head> tag OR before </body>
Related
I want to calculate my input box inner looping and this bellow is what if done please help me to solve this issue
<?php
$jumlah_form = 3;
for($i=1; $i<=$jumlah_form; $i++){
?>
<input type="text" id="txt1" onkeyup="sum1();" /></br>
<?php
}
?>
<input type="text" id="txt2" value= "0" /></br>
<script>
function sum1() {
var txtFirstNumberValue = document.getElementById('txt1').value;
var txtSecondNumberValue = document.getElementById('txt2').value;
var result = parseInt(txtFirstNumberValue) + parseInt(txtFirstNumberValue) ;
if (!isNaN(result)) {
document.getElementById('txt2').value = result;
}
}
</script>
Three input boxes are created by looping, I want to calculate three input box, and parse the result into result box whenever user input number
I think you are asking how to write the JavaScript so that it will add up the total of all the input boxes, no matter how many are created by the PHP?
If so then a good way would be to give all the textboxes the same class. Then, the JavaScript can just select all boxes with that class, loop through them and get the total value.
Here's a worked example using 3 textboxes (as if the PHP had generated them this way):
var textboxes = document.querySelectorAll(".sum");
textboxes.forEach(function(box) {
box.addEventListener("keyup", sumAll);
});
function sumAll() {
var total = 0;
textboxes.forEach(function(box) {
var val;
if (box.value == "") val = 0;
else val = parseInt(box.value);
total += val;
});
document.getElementById("total").innerText = total;
}
<input type="number" id="txt1" class="sum" value="0" /><br/>
<input type="number" id="txt2" class="sum" value="0" /><br/>
<input type="number" id="txt3" class="sum" value="0" /><br/>
<br/><br/> Total: <span id="total"></span>
To generate html with php:
$count = 5;
for($i=1;$i <= $count;$i++) {
echo "<input type='number' id='"."txt".i."' /></br>"
}
To calculate sum from inputs:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello World</title>
</head>
<body>
<form onsubmit="submitForm(this); return false;" >
<input type="number" id='text1'>
<input type="number" id='text2'>
<input type="number" id='text3'>
<input type="number" id='text4'>
<input type="number" id='text5'>
<button type="submit" >Calculate</button>
</form>
<div>
<p>Result:</p>
<p id='result'></p>
</div>
<script>
function submitForm(form) {
let toReturn = 0;
const inputs = form.getElementsByTagName("input");
for(let x = 0; x < inputs.length; x++ ) {
toReturn += parseInt(inputs[x].value ? inputs[x].value : 0);
}
document.getElementById('result').innerHTML = toReturn;
return false;
}
</script>
</body>
</html>
I have a PHP project containing textboxes to visualize STACK data structure concept; as seen in the screenshot below:
I am passing PHP values to JavaScript function and adding value only to the index number where there is no value (i.e Top of stack)
Below is the code:
<html>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Data Structure Visualization</title>
<link rel=stylesheet href=StackStyleSheet.css>
<script type="text/javascript">
function addElement($id, $value)
{
var id = $id;
var value = $value;
//correct id and value is passed here.
var textbox = document.getElementById(id);
//this LOC does not execute and returns to the php code
textbox.value = value;
}
</script>
<body>
<?php include 'header.php'; ?>
<form method="POST" action="">
<div id ="container">
<div id="top">
<h3>STACK (ARRAY IMPLEMENTATION)</h3>
</div>
<div id="bottom">
<input id="inputBox" type="text" name="inputNumber" value="">
<button id="pushButton" type="submit" class="button button1" name = "PUSH">Push</button>
<button id="popButton" type="submit" class="button button2" name = "POP">Pop</button>
<button id="clearButton" type="submit" class="button button3" name = "CLEAR">Clear Stack</button>
</div>
<div id="operation">
<input type="text" name="5E" value="" class="operation1 obutton6">
<input type="text" name="4E" value="" class="operation1 obutton5">
<input type="text" name="3E" value="" class="operation1 obutton4">
<input type="text" name="2E" value="" class="operation1 obutton3">
<input type="text" name="1E" value="" class="operation1 obutton2">
<input type="text" name="0E" value="" class="operation1 obutton1">
</div>
</div>
</form>
<?php
include 'footer.php';
if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['PUSH']))
{
$val0E = (int)$_POST['0E'];
$val1E = (int)$_POST['1E'];
$val2E = (int)$_POST['2E'];
$val3E = (int)$_POST['3E'];
$val4E = (int)$_POST['4E'];
$val5E = (int)$_POST['5E'];
//creating an associative array to store/add/delete values in the index locations
$elementsindex = array("0E"=>$val0E ,"1E"=>$val1E,"2E"=>$val2E, "3E"=>$val3E, "4E"=>$val4E, "5E"=>$val5E);
foreach ($elementsindex as $key => $value)
{
if(($elementsindex[$key])==null)
{
//value copied from textbox
$id = $key;
$value = $_POST['inputNumber'];
//value pushed in
$elementsindex[$key] = $value; //saves value against element index
//value reflected on screen box
echo '<script type="text/javascript">';
echo 'addElement("'.$id.'", "'.$value.'");';
echo '</script>';
break;
}
else if(($elementsindex[$key])!=null)
{
continue;
}
}
}
}
</body>
</html>
In the foreach loop, if the value at bottom index i.e index = 0E is null/zero, then a new value is added to it, after which we exit from the loop using break;
But, at the JavaScript function addElement(), the following code does not execute and immediately returns and no value is filled in the textbox.
var textbox = document.getElementById(id);
//this LOC does not execute and returns to the php code
textbox.value = value;
Where is the code wrong?
I have a website that when the user leaves any of the text fields blank, the border of the box will turn red. I figured it out in css with these lines of code
.input-box{
border-color: red;
}
.input-box:focus{
outline: none;
}
But I want to implement this in my php code if the fields are empty. I've been searching this all around an cannot find a solution. I even tried JavaScript and got to this point
if(empty($fullname)){
echo "
<script type=\"text/javascript\">
document.getElementByClassName('input-box').style.borderStyle = 'solid';,
document.getElementByClassName('input-box').style.border = '';,
document.getElementByClassName('input-box').style.borderColor = 'red';
</script>
";
}
if(empty($email)){
echo "
<script type=\"text/javascript\">
document.getElementByClassName('input-box').style.borderStyle = 'solid';,
document.getElementByClassName('input-box').style.border = '';,
document.getElementByClassName('input-box').style.borderColor = 'red';
</script>
";
}
if(empty($password)){
echo "
<script type=\"text/javascript\">
document.getElementByClassName('input-box').style.borderStyle = 'solid';,
document.getElementByClassName('input-box').style.border = '';,
document.getElementByClassName('input-box').style.borderColor = 'red';
</script>
";
}
if(!empty($fullname) && !empty($email) && !empty($password)){
echo "you're in";
}
But it is not working. So all I want to do is when the user leaves a field empty, the border of the box will turn red and the outline will be none.
getElementsByClassName returns an array, so you cannot assign properties like style.
Here's the JavaScript you want:
var inputs= document.getElementsByClassName("input-box");
for(var i=0; i<inputs.length; i++) {
inputs[i].style.borderStyle = 'solid';
inputs[i].style.border = '';
inputs[i].style.borderColor = 'red';
}
My Code is based on jQuery.
Hope It will help you...
$('#user-form').submit(function(e) {
var name = $('#name').val();
var email = $('#email').val();
var phone = $('#phone').val();
var address = $('#address').val();
var dob = $('#dob').val();
if(name=="") $('#name').addClass('input-box'); else $('#name').removeClass('input-box');
if(email=="") $('#email').addClass('input-box'); else $('#email').removeClass('input-box');
if(phone=="") $('#phone').addClass('input-box'); else $('#phone').removeClass('input-box');
if(address=="") $('#address').addClass('input-box');else $('#address').removeClass('input-box');
if(dob=="") $('#dob').addClass('input-box'); else $('#dob').removeClass('input-box');
if((name=="")||(email=="")||(phone=="")||(address=="")||(dob==""))event.preventDefault();
});
.input-box{
border-color: red;
}
.input-box:focus{
outline: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" id="user-form" action="q.php">
<p><label>Name : </label><input type="text" id="name" name="name" /></p>
<p><label>Email : </label><input type="text" id="email" name="email" /></p>
<p><label>Phone : </label><input type="text" id="phone" name="phone" /></p>
<p><label>Address : </label><input type="text" id="address" name="address" /></p>
<p><label>DOB : </label><input type="text" id="dob" name="dob" /></p>
<p><button type="submit" id="submit">Submit</button></p>
</form>
While I am not a big fun of mixing PHP/server code with front end like that, there is an obvious error (unless it was intended). Since you are using class input-box for all, if any one field is empty, all will be marked as empty.
Anyway, try the following:
first, the styles you want to apply for empty fields are the same. So, in your css file define one. E.g.
.needed-field {border:1px solid red;}
Then give each field a unique id while keeping the class input-box in place.
Then do two things in your PHP file: remove any possible bad field from before when submitting the form or something:
$('.input-box').removeClass('needed-field');
Then for each one:
if(empty($fullname)){
echo "
<script type=\"text/javascript\">
$('#fullname').addClass('needed-field');
</script>
";
}
Hope that helps.
Edit:
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<style>
.needed_field {border:5px solid red;}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<form action="so/1.php" method="post">
<input type="text" id="fullname" name="fullname" class="input-box"><br/>
<input type="text" id="email" name="email" class="input-box"><br/>
<input type="text" id="password" name="password" class="input-box"><br/>
<input type="submit" value="Sumbit" id="submit" name="submit">
</form>
<script>
$('.input-box').removeClass('needed_field');
<?php
if($_POST['submit']){
//echo '<script>'
//echo '</script>';
$fullname=$_POST['fullname'];
$email=$_POST['email'];
$pwd=$_POST['pwd'];
if(empty($fullname)){
echo "$('#fullname').addClass('needed_field');";
}
}
?>
</script>
</body>
</html>
I can't get this to work.
I got two forms, "mult" and "mult2" with a script making some simple calculations running through both. Both fields are dependent on data in another form called "recipe".
The thing is, i can actually get one of the forms to work doing it like i have done (see all my code under here) - the weird thing is that it's only mult2 that works and does all the calculations. Mult1 is not doing anything. The fields that needs to be updated in the end is "gravity" and "gravity2" - and only "gravity2" gets updated with the result of the calculation.
I know it's some long code bits here, but hope you can help me..
Here is the "recipe" form:
<form name="recipe">
<input type="text" size="1" maxlength="3" name="batchVal" value="30" onChange="calculate(malt1); calculate(malt2)"></td>
<input type="text" size="1" maxlength="3" name="efficiencyVal" value="75" onChange="calculate(malt1); calculate(malt2)"></td>
</form>
Here is the two forms, "mult" and "mult2" that both need the same datainputs from "recipe" form:
<form name="mult">
<select id="malt" name="malt" onChange="UpdateNextField(this,'ppg')">
<option>Choose fermentable..</option>
<?php
$query = $mysqli->prepare("SELECT id,maltname,maltebc,maltppg FROM malt WHERE mainid = ?");
$mainidcolumn = "1";
/* bind parameters */
$query->bind_param("i", $mainidcolumn);
$query->execute();
$menu_result = $query->get_result();
/* now you can fetch the results into an array */
while ($menu = $menu_result->fetch_assoc()) {
echo '<option value="'.$menu['maltppg'].'">' . $menu['maltname'] . ' ' . $menu['maltebc'] . ' EBC</option>';
}
echo '</select>';
?>
<input type="text" id="ebcfield" size="1" maxlength="3">
<input type="text" name="weightVal" size="1" maxlength="5" value="0" onChange="calculate(malt1)">
<input name="grainpercent" type="text" id="grainpercent" size="1" maxlength="2">
<input type="text" id="gravity" size="1" value="0" maxlength="4">
<input name="graincolor" type="text" id="graincolor" size="1" maxlength="3">
<input type="text" name="ppgVal" id="ppg" onMouseMove="calculate(malt1)">
</form>
<form name="mult2">
<select id="malt" name="malt" onChange="UpdateNextField(this,'ppg2')">
<option>Choose fermentable..</option>
<?php
$query = $mysqli->prepare("SELECT id,maltname,maltebc,maltppg FROM malt WHERE mainid = ?");
$mainidcolumn = "1";
/* bind parameters */
$query->bind_param("i", $mainidcolumn);
$query->execute();
$menu_result = $query->get_result();
/* now you can fetch the results into an array */
while ($menu = $menu_result->fetch_assoc()) {
echo '<option value="'.$menu['maltppg'].'">' . $menu['maltname'] . ' ' . $menu['maltebc'] . ' EBC</option>';
}
echo '</select>';
?>
<input type="text" id="ebcfield" size="1" maxlength="3">
<input type="text" name="weightVal2" size="1" maxlength="5" value="0" onChange="calculate(malt2)">
<input name="grainpercent" type="text" id="grainpercent" size="1" maxlength="2">
<input type="text" id="gravity2" size="1" value="0" maxlength="4">
<input name="graincolor" type="text" id="graincolor" size="1" maxlength="3">
<input type="text" name="ppgVal2" id="ppg2" onMouseMove="calculate(malt2)">
</form>
And finally the javascript that does the calculations based on data in the input fields. Calculate(malt1) and Calculate(malt2) does the same thing, it's just two instances of the same calculation.
<script type = "text/javascript">
function UpdateNextField(which,ppg) {
document.getElementById(ppg).value = which.value;
}
function UpdateNextField(which,ppg2) {
document.getElementById(ppg2).value = which.value;
}
</script>
<!-- calculations for malt 1-5 -->
<!-- form 1 - fermentable 1 -->
<script type="text/javascript">
function calculate(malt1){
var weightVal = document.mult.weightVal.value;
var ppgVal = document.mult.ppgVal.value;
var batchVal = document.recipe.batchVal.value;
var efficiencyVal = document.recipe.efficiencyVal.value;
var showValue = 0;
var showValue = ((weightVal * ppgVal * 0.000008345) * (efficiencyVal) * 10) / batchVal + (1000);
showValue = Math.round(showValue * 1) / 1;
if (!isNaN(showValue)) {
document.getElementById('gravity').value = showValue;
}
}
function calculate(malt2){
var weightVal2 = document.mult2.weightVal2.value;
var ppgVal2 = document.mult2.ppgVal2.value;
var batchVal = document.recipe.batchVal.value;
var efficiencyVal = document.recipe.efficiencyVal.value;
var showValue2 = 0;
var showValue2 = ((weightVal2 * ppgVal2 * 0.000008345) * (efficiencyVal) * 10) / batchVal + (1000);
showValue2 = Math.round(showValue2 * 1) / 1;
if (!isNaN(showValue2)) {
document.getElementById('gravity2').value = showValue2;
}
}
</script>
You have a few problems with your function names and duplicate IDs, as noted by Jay and LcLk. But, assuming you fix these, you can save a lot of time and grief by using jQuery. For example:
HTML
<input type="text" id="first" />
<input type="text" id="second" />
Javascript
$("#first").keypress(function(){
/* your custom code goes here */
console.log("A key was pressed.");
});
What this says is that anytime a key is pressed while the first input is selected, it will print out A key was pressed in the console. You can then either directly call your calculation functions from within that anonymous inner function, or pass them directly into keypress();.
I want to pass values to a PHP script so i am using AJAX to pass those and that part works. But in the same function I want retrieve those values that I passed to the PHP script. The problem is I cannot retrieve any value from the PHP file. I have search high and low, but now come to you for answers. How can I store the variable passed on to the PHP script so that my ajax can retrieve it? My code is as follows:
This is my form :
<!-- file album.php -->
<html>
<head>
<?PHP
include ("conection/connect.php");
?>
<script type="text/javascript" src="jstbl/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
function cekjumlah(tableID)
{
var hitung=document.getElementById(tableID).rows.length;
var jumlah = hitung-1;
document.getElementById("media").value=jumlah;
}
</script>
</head>
<title></title>
<body>
<form name="form1" id="form1" method="post">
Jumlah Inputan :
<input type="text" id="media" name="media" size="5">
<input type="text" id="data_barang" name="data_barang" size="60" onKeyPress="onEnterPenjualan(event);">
<br><br>
<table id="tabelimei" border="1">
<tr id="Last">
</tr>
</table>
<br><br>
<div id="menu">
<p>
<input type="submit" name="simpan" value="Simpan" onClick="cekjumlah('tabelimei')">
<input onClick="deleteRow('DivTambah')" name="button" type="submit" value="Hapus" />
</p>
<p id="hasil">hasil</p>
</div>
</form>
</body>
</html>
And this is my jquery :
function onEnterPenjualan(e){// => Digunakan untuk membaca karakter enter
var key=e.keyCode || e.which;
if(key==13){// => Karakter enter dikenali sebagai angka 13
$(function(){
var data_barang = $("#data_barang").val();
$.ajax({
url: "ambildatabarang.php",
data: "data_barang="+data_barang,
cache: false,
success: function(data){
console.log(data);
alert(data);
}
});
var nama = alert (data.$nama);
var baris = document.getElementById("data_barang").value;
var i = 1;
var row = $(document.createElement('tr')).attr("id", 'DivTambah' + i);
row = '<tr>'+
'<td>1</td>'+
'<td><input name="cek[0]" id="cek" type="checkbox" size="10" /></td>'+
'<td><input name="qty_penjualan[0]" type="text" id="qty_penjualan" value="1" size="10" required/></td>'+
'<td><input type="text" name="imei_penjualan[0]" id="imei_penjualan" size="60" value="'+baris+'" required/></td>'+
'<td><input type="text" name="nama_penjualan[0]" id="nama_penjualan" size="30" value = "'+nama+'"required/></td>'+
'<td><input type="text" name="hargajual_penjualan[0]" id="hargajual_penjualan" value="300000" size="15" required/></td>'+
'<td><input type="text" name="diskon_penjualan[0]" id="diskon_penjualan" size="15" value="0"/></td>'+
'<td><input type="text" name="total_penjualan[0]" id="total_penjualan" size="15" value="300000" required/></td>'+
'<td><button type="button" class="del">Del</button></td>'+
'</tr>';
$(row).insertBefore("#Last");
var hapus = "";
document.getElementById('data_barang').value=hapus;
document.getElementById('data_barang').value.focus();
i++;
});
$(".del").live('click', function(){
$(this).parent().parent().remove();
});
}}
And this is my PHP file :
<?php
if (isset($_GET['data_barang'])){
// Instructions if $_POST['value'] exist
include ("conection/koneksidb.php");
$databarang = $_GET['data_barang'];
$datalengkapbarang = mysql_query("SELECT i.id_imeibarang, jb.nama_jenisbarang, b.type_barang, b.hargajual_barang FROM jenisbarang jb, barang b, imeibarang i WHERE i.id_imeibarang='$databarang' and i.idbarang_imeibarang=b.id_barang and b.idjenis_barang=jb.id_jenisbarang");
$angka = 1;
while($k = mysql_fetch_array($datalengkapbarang)){
echo $no[$angka] = $angka;
echo $imei[$angka]=$k['id_imeibarang'];
echo $nama[$angka]=$k['nama_jenisbarang'].$k['type_barang'];
echo $harga[$angka]=$k['hargajual_barang'];
$angka = $angka+1;
}
}
?>
to send the some data to php and get the result of the php file to javascript synchronously, this is what you need
function sendData (data1,data2)
{
if (window.XMLHttpRequest)
AJAX=new XMLHttpRequest();
else
AJAX=new ActiveXObject("Microsoft.XMLHTTP");
if (AJAX)
{
AJAX.open("POST", "url.php", false);
AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
AJAX.send("data1=" + data1 + "&data2=" + data2);
return AJAX.responseText;
}
else
return null;
}
now, on your php file, you just get your data like this
$data1 = $_POST['data1'];
$data2 = $_POST['data2'];
once you work with the data in your php file, and then you echo the result, it is returned by the javascript function, so you just need to use it like this in your javascript file
var data_from_php = sendData(data1,data2);