I am using the code below for users to select a thumbnail from a PHP array of images in a form. I am trying to figure out a way so that when the user submits the form this is on, which ever image is displayed currently will be passed through the form to the PHP Post. I'm not sure how to do this. Logically think of it as, if image[1] is active, I want to send that url to the form. Currently, the PHP var $knoteImgs[] are full tags, if I need to put the img tag in the JS it may be cleaner to obtain the URL.
<script type="text/javascript">
var image = new Array(3)
image[1]="<? echo $knoteImgs[0]; ?>"
image[2]="<? echo $knoteImgs[1]; ?>"
image[3]="<? echo $knoteImgs[2]; ?>"
var num = 1;
document.getElementById('next').addEventListener('click', function(galleryNext){
num=num+1
if (num==4)
{num=1}
document.getElementById('knoteImg').src=image[num];
});
document.getElementById('back').addEventListener('click', function(galleryPrevious){
num=num-1
if (num==0)
{num=3}
document.getElementById('knoteImg').src=image[num];
});
</script>
Edit: if anyone could even link me to some relevant posts that would be useful. In not sure what to search for.
Edited my original post to show working code:
Thanks to #GaryHayes and #Brad for the assistance!
<script type="text/javascript">
var image = <?php echo json_encode($knoteImgs); ?>;
var tot = image.length;
var c = 0; // current image (array key index)
function loadImage(){
$("<img/>").attr({src:image[c], id:"knoteImg", class:"img-thumbnail"}).load(function() {
$('#thumbnail').html( this );
});
}
loadImage(); // load 1 image
$('#prev, #next').click(function(){
id= this.id==='next' ? c++ : c-- ;
c= c==-1 ? tot-1 : c%tot ;
loadImage();
});
function getimage() {
document.getElementById('currentimage').value = document.getElementById('knoteImg').src;
var thumbnail = document.getElementById('currentimage');
alert(thumbnail.value);
}
</script>
alert(thumbnail.value); is triggered by:
<input type="hidden" id="currentimage" name="currentimage" />
<input type="submit" onclick="getimage();" value="Submit" />
Your HTML in form:
<input type="hidden" id="currentimage" name="currentimage" />
<input type="submit" onclick="getimage();" value="Submit" />
Your Function in Javascript:
function getimage() {
document.getElementById('currentimage').value = document.getElementById('knoteImg').src;
}
SOmething like this... sorry if not perfect... not testing live.
Related
I created an instant search similar to google search using JQuery. The highlighted code doesn't work. It is weird since they work fine by its own and everything else works fine. Any idea why this is happening?
Q1.
searchq() works fine, but the createq() function doesn't work, and the variable txt could be posted to other files(search.php). However, the function createq() can't POST. It does get the global variable txt after testing, but the php file(create_object.php) can't get it no matter what POST method I used. Could anyone helps to write a bit POST code which can work in my code.
Q2
I want to create a function that,when the enter is pressed, the user will be redirected to the first search result(which is anchored with an url) . To achieve this, I create a function that variable redirectUrl got the anchored url as string, however, the redirect function window.location.href doesn't work, the page simply refreshed. I tested window.location.href function by its own in another file, it works though. It is so weird that my page simply refreshed, It even refreshed when I direct to google. window.location.href("www.google.com").
Note that I didn't include the connect to database function here. Coz I think the database username and password setting would be different to yours.So please create your own if you want to test it. The mysql is set with a table is called "objects", and it has one column named "name".
Thanks in advance!
<html>
<!-- google API reference -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<!-- my own script for search function -->
<center>
<form method="POST">
<input type="text" name="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
<div id="output">
</div>
</form>
</center>
<!-- instant search function -->
<script type="text/javascript">
function searchq(){
// get the value
var txt = $("input").val();
// post the value
if(txt){
$.post("search.php", {searchVal: txt}, function(result){
$("#search_output").html(result+"<div id=\"create\" onclick=\"creatq()\"><br>Not found above? Create.</div>");
});
}
else{
$("#search_output").html("");
}
};
function createq(){
// allert for test purpose: test if the txt has got by the createq function
alert(txt);
**$.post( "create_object.php",{creatVal:txt} );**
}
// if enter key pressed, redirect page to the first search result
$("#search").keypress(function(evt){
if (evt.which == 13) {
// find the first search result in DOM and trigger a click event
var redirectUrl = $('#search_output').find('a').first().attr('href');
alert(redirectUrl);
**window.location.href = "www.google.com";
window.location.href = "www.google.com";**
}
})
</script>
</html>
PHP file (search.php)
<?php
if(isset($_POST["searchVal"])){
//get the search
$search=$_POST["searchVal"];
//sort the search
$search=preg_replace("#[^0-9a-z]#i","",$search);
//query the search
echo "<br/>SELECT * from objects WHERE name LIKE '%$search%'<br/>";
$query=mysqli_query($conn,"SELECT * from objects WHERE name LIKE '%$search%'") or die("could not search!");
$count=mysqli_num_rows($query);
//sort the result
if($count==0){
$output="there was no search result";
}
else{
while($row=mysqli_fetch_assoc($query)){
$object_name=$row["name"];
$output.="<div><a href='##'>".$object_name."</a></div>";
}
}
echo $output;
}
?>
php file (create_object.php)
<?php
if(isset($_POST["createVal"])){
$name=$_POST["createVal"];
var_dump($name);
}
?>
Try to bind the input with id
var txt = $("input").val();
<input type="text" name="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
Change above to this
var txt = $("#searchinput").val();
<input type="text" id="searchinput" name="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
and I think you are trying to show the search result here
<div id="output"></div>
and the jQuery binding is this in your code
$("#search_output").html("");
So change the HTML to this
<div id="search_output"></div>
also this in our code
$("#search").keypress(function(evt){
there is not HTML element bind with it and I think you are trying to bind it with search input so change above to this
$("#searchinput").keypress(function(evt){
The above change should also resolve the window.location.href not working problem
So the HTML will be;
<form method="POST">
<input type="text" id="searchinput" name="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
<div id="search_output"></div>
</form>
and Script will be
<script type="text/javascript">
function searchq(){
// get the value
var txt = $("#searchinput").val();
// post the value
if(txt){
$.post("search.php", {searchVal: txt}, function(result){
$("#search_output").html(result+"<div id=\"create\" onclick=\"creatq()\"><br>Not found above? Create.</div>");
});
}
else{
$("#search_output").html("");
}
}
function createq(){
// allert for test purpose: test if the txt has got by the createq function
alert(txt);
**$.post( "create_object.php",{creatVal:txt} );**
}
// if enter key pressed, redirect page to the first search result
$("#searchinput").keypress(function(evt){
if (evt.which == 13) {
// find the first search result in DOM and trigger a click event
var redirectUrl = $('#search_output').find('a').first().attr('href');
alert(redirectUrl);
**window.location.href = "www.google.com";
window.location.href = "www.google.com";**
}
});
</script>
Note: If you check browser console, you may see some errors, there are some typo mistakes like missing ; in your JS too.
In the PHP, here
if($count==0){
$output="there was no search result";
}
else{
while($row=mysqli_fetch_assoc($query)){
$object_name=$row["name"];
$output.="<div><a href='##'>".$object_name."</a></div>";
}
}
$output. is wrong with dot, so change it to following
if($count==0){
$output="there was no search result";
}
else{
while($row=mysqli_fetch_assoc($query)){
$object_name=$row["name"];
$output="<div><a href='#'>".$object_name."</a></div>";
}
}
Two things:
Input search id is not defined, $("#search").keypress won't work. Change to:
< input type="text" name="search" id="search" style="width:400px " placeholder="Search box" onkeyup="searchq();" >
Div id "output", should be "search_output", as required in $("#search_output"). Change to:
< div id="search_output" >
< /div >
The user needs to enter the 4 input fields in order to get the result which is expense. The result will be using FV formula thus I searched online and found out the how FV formula can be used in PHP. Now i want to call the function of the FV formula using the jQuery as i want when the user entered all fields the results will auto come out in the id rExpenses but it doesn't work. It displays a blank page when I go the localhost. Can anyone help? Thank you!
Edit: I deleted the php part and change the code to:
<!doctype html>
<html>
<script>
$(document).ready(function() {
$('input').keyup(function(){
var $rincome = parseInt($('#textfield1').val());
var $rate = parseInt($('#textfield2').val());
var $age = parseInt($('#textfield3').val());
var $rage = parseInt($('#textfield4').val());
var rExpenses = FV($rate/100,$rage - $age ,0,$rincome,0);
$('#rExpenses').html((rExpenses).toFixed(2));
});
});
</script>
<b>Monthly retirement income (SGD):</b>
<input type="number" id="textfield1" value="<?php echo $_POST['rincome'];?>" name="rincome" min = "0" />
</p>
<p>
<b>Inflation rate (%):
<input type="number" id="textfield2" value="<?php echo $_POST['rate'];?>" name="rate" min = "0" step = "0.1"/>
</p>
<p>
<b>Current age:
<input type="number" id="textfield3" value="<?php echo $_POST['age'];?>" name="age" min = "0" max = "70"/>
</p>
<p>
<b>Retirement age:
<input type="number" id="textfield4" value="<?php echo $_POST['rage'];?>" name="rage" min = "0"/>
</p>
<p>
<b>The monthly expenses when you retire(inflation adjusted):<span id = "rExpenses">$0.00</span>
</p>
<script>
function FV(rate, nper, pmt, pv, type) {
var pow = Math.pow(1 + rate, nper),
fv;
if (rate) {
fv = (pmt*(1+rate*type)*(1-pow)/rate)-pv*pow;
} else {
fv = -1 * (pv + pmt * nper);
}
return fv.toFixed(2);
}
</script>
</html>
You can't call a PHP function from within JQuery because JQuery is running in the browser, and PHP is running on the server. You could do it as a remote sort of thing using an AJAX call, but that would be silly. Why not just translate the PHP function into Javascript, and have it on the page?
Looking at the page, I can see what you've done, and it looks like you're wanting to have the server do the calculation. If you want to do that, you'll probably have to create a form and post your values to the server, or, as I said above, do something with AJAX.
If it were me, I'd get rid of the PHP stuff, and have something like this instead (and yes, you can use $ signs in variable names in Javascript, but I'd recommend against this if you're going to mix PHP up with it):
$('input').keyup(function(){
var $rincome = parseInt($('#textfield1').val());
var $rate = parseInt($('#textfield2').val());
var $age = parseInt($('#textfield3').val());
var $rage = parseInt($('#textfield4').val());
var rExpenses = fv($rate/100,$rage - $age ,0,$rincome);
$('#rExpenses').html((rExpenses).toFixed(2));
});
then change your <?php and ?> tags at the end of the page into <script> and </script> tags. It won't work exactly, but you should be able to debug it easily enough in your browser tools.
I think you are confusing two concepts here. PHP runs on server, which means when you call that php function, the result is a html file without any of the php code. So you cannot directly call php function in jquery, which runs on the generated HTML file.
I think translating the php function to a javscript function, which can be directly called is the best option you have now.
The translated javascript function is as easy as below:
function fv(r,n,p,pv=0)
{
var sum = pv;
for (var i=0;i<n;i++ )
{
sum += sum*r + p;
}
return sum;
}
Then your jquery script block becomes
$(document).ready(function() {
$('input').keyup(function(){
var rExpenses = fv(("#textfield2").val()/100, ("#textfield4").val() - ("#textfield3").val(), 0, ("#textfield1").val());
$('#rExpenses').html((rExpenses).toFixed(2));
});
});
I've been struggling for a while with a problem, which I believe is very simple, yet I'm unable to solve. Can you tell me how to pass data to my function in the current example.
The situation is as follows
I'm generating new form elements with a button. But I would like to add the functionality of counting the word count for the new textareas, currently I'm able to just make it work for the first inputs.
HTML
<textarea class="cTxtW-<?php echo $k;?>" type="text" placeholder="50 word description"></textarea>
<p id="count-<?php echo $k;?>"></p>
<script>
$( ".cTxtW-<?php echo $k;?>" ).keyup(function count('.cTxtW-<?php echo $k;?>', 'count-<?php echo $k;?>'));
</script>
At the top of the page is my javascript
<script type="text/javascript">
function count(txt, cnt){
var txtVal = $(txt).val();
var words = txtVal.trim().replace(/\s+/gi, ' ').split(' ').length;
var chars = txtVal.length;
if(chars===0){words=0;}
$(cnt).html(words+' words');
}
</scirpt>
I'm adding new fields with the following code
var addDivS = $('#addServ');
var k = parseInt($("#lS").attr('rel'))+1;
$('#addNewServ').on('click', function() {
if(k<=5){
var inputsS = '<textarea name="servTxt[]" style="margin:10px 0 0 0;width:560px;height:60px;" class="inpt cTxtW-'+k+'" type="text" placeholder="50 word description"></textarea><p id="count-'+k+'"></p>'
$(inputsS).appendTo(addDivS);
k++;}else alert('Maximum number of contacts reached.')
return false;
});
So my question is - how to show my word count based on the newly generated textarea field?
This should work...
<script>
$( ".cTxtW-<?php echo $k;?>" ).keyup(function () {
count('.cTxtW-<?php echo $k;?>', 'count-<?php echo $k;?>');
});
</script>
You were passing in the result of the count function as an event handler for keyup. By putting it in an anonymous function it will only run it when the even takes place.
I'm trying to get the value in my input field to be put into my post statement to be sent to my php file to update the record without reloading the page. It works fine with static information that I put in but when I want to select what I have typed in the input box, i can't get it to work. Nothing happens.
<script src="../jquery.js"></script>
<script type="text/javascript">
function editItem() {
catno = $("#catno").attr('value');
id = $("#id").attr('value');
$.post('writeToDB.php', {
id: id,
catno: catno
});
}
</script>
</head>
<body>
<form id="foo">
<input type="hidden" value="<?php echo $row_Recordset1['ID']; ?>" name="id"
id="id" />
<input type="text" value="<?php echo $row_Recordset1['CAT_NO']; ?>" name="catno"
id="catno" onchange="editItem();" />
</form>
I'm new to this javasrcipt world and jquery but I'm at the piont of pulling my hair out. I'm probably doing something really stupid
Thanks
Change
catno = $("#catno").attr('value');
id = $("#id").attr('value');
to
var catno = $("#catno").val();
var id = $("#id").val();
Use .val() to retrieve the value of an input.
You should also prefix your locally declared variables with var - this question/answer has a good explanation why
call val() method
id = $("#id").val();
val() method get the current value of the first element in the set of
matched elements
so your code will be
function editItem() {
var catno = $("#catno").val();
var id = $("#id").val()
$.post('writeToDB.php', {
id: id,
catno: catno
});
}
Use .val() :
http://api.jquery.com/val/
I'm working on a little parsing thing to color objects.
For an example, you could type red:Hi!: and "Hi!" would be red.
This is my not working code:
<script type="text/javascript">
function post()
{
var preview = document.getElementById("preview");
var submit = document.getElementById("post");
var text = submit.value;
<?php str_replace("red:*:",'<i class="red">*</i>',text); ?>
preview.value = text;
}
</script>
You have at least two massive problems here.
You can't str_replace with wildcards like you are (the asterisks you use are just that - the asterisk character, not a placeholder).
Your idea of the page-rendering process is off - you can't just call some PHP code in JavaScript and have it update the page. Any PHP code will be executed and printed when your page is generated on the server - it can't interact with the page like JavaScript can (JS can because it is executed within the browser, but the browser never actually sees your PHP code as you can check by going to View->Source and seeing what you see). You certainly cannot reference a JavaScript variable from PHP.
Two options.
Option 1 - Proper Server-Side
if you want to colour objects on page load based on post, do something like this:
<?php
# If the value was posted
$raw = isset($_POST['userstring']) ? $_POST['userstring'] : "";
# Split it based on ':'
$parsed = explode(':', $raw);
$colorClass = "";
$text = "";
if (count($parsed) >= 2)
{
$colorClass = $parsed[0];
$text = $parsed[1];
}
?>
<form action="" method="post">
<input type="text" name="userstring" value=""/>
<input type="submit" value="Submit" />
</form>
<div id="preview">
<?php if (strlen($text) > 0) { ?>
<i class="<?php echo $colorClass; ?>">
<?php echo $text; ?>
</i>
<?php } ?>
</div>
Option 2 - Proper Client-Side
Include jQuery in your <head> tag to make your life easier. If you really don't want to include jQuery you can still change the jQuery calls to your getElementById etc. (you'll want to replace the html() call with '.innerhtml' I think - just look it up).
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</script>
<script type="text/javascript">
function post() {
var split = $('#userinput).val().split(separator, limit)
if (split.length >= 2) {
var color = split[0];
var text = split[1];
$('#preview').html('<i class="' + color + '">' + text + '</i>');
}
return false; // Stop form submit
}
</script>
<form action="" method="post" onsubmit="post()">
<input id="userinput" type="text" name="userstring" value=""/>
<input type="submit" value="Submit" />
</form>
<div id="preview">
</div>
</body>
You're mixing server and client side technologies here. The code in the php lock is evaluated once (while still on the server). You're looking for something that will operate entirely on the client side.
This means you need to look into Javascript regular expressions, instead of PHP preg_match type stuff.
http://www.regular-expressions.info/javascriptexample.html
You're looking for this type of thing:
stringObject.replace( regularExpressionVarOrLiteral, replacement );
Josh