How to pass a Javascript ID value into a form Placeholder? - javascript

I have used a function to capture the Query String value of "name" - i.e. imagine a party invite site;
https://cometomyparty.com?name=phil
The function used is;
script type="text/javascript">
function getQuerystring(){
var q=document.location.toString();
q=q.split("?");
q=q[1].split("&");
var str=""
for(i=0;i<q.length;i++){
tmp=q[i].split("=")
str+=" "+tmp[1]+"<br />"
}
document.getElementById("name").innerHTML=str
}
onload=function(){
getQuerystring()
}
</script>
Then I can call the value of 'name' using id="name" where I want to use this on my page, i.e. in the heading, I could say, Phil, looking forward to having you at the party...
That's working well. The problem I have is, I have a Form I'm using as well, and within that, it has a Placeholder field, like so;
<div class="form-section">
<input type="text" name="name" class="validate-required" placeholder="Names">
How can I insert my 'id' value of 'name' into my placeholder here? The end result would be, the invite mechanic would work on the same URL, across multiple invitees, but the URL would just change. The RSVP form would reflect what is in the URL as the placeholder, yet the user could still update it if it was incorrect.
Any advice appreciated.

This find placeholder and change using jquery
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#name').attr("placeholder", "your place holder here");
});
</script>
if it's a $var also don't need quotes would be like
$('#name').attr("placeholder", $str);
Or using javascript
<script type="text/javascript">
function getQuerystring(){
var q=document.location.toString();
q=q.split("?");
q=q[1].split("&");
var str=""
for(i=0;i<q.length;i++){
tmp=q[i].split("=");
str+=" "+tmp[1]+"<br />";
}
document.getElementById("name").innerHTML=str;
document.getElementById("name").placeholder=str;
}
onload=function(){
getQuerystring();
};
</script>
document.getElementById("name").placeholder="value here" if it's a var so don't need quotes
Also you need to insert an id to your html input field
<div class="form-section">
<input type="text" id="name" name="name" class="validate-required" placeholder="Names">

Related

Javascript two weird problems: POST not working, window.location.href not working

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 >

Multiply parameter and textBox value in JavaScript

I have an input text box that is in a form, and I'm trying to retrieve the value and multiply it to the parameter.
It doesn't run and I'm not sure if there's a syntax error or if my retrieval of textbox value is incorrect.
<script>
function product(parameter1) {
a=parseInt(document.myForm.myTextBox.value);
return parameter1*a;
};
</script>
HTML:
<form name='myForm'>
Insert your number: <input id='myTextBox' value=''><br>
</form>
<input type='button' value='CLICK HERE' onclick='product()'>
You miss an argument in the onclick trigger, it should be ="product(10)", where 10 is your paremeter1 argument.
I believe you would have to have a name on the input tag to access it the way you do, so an easier and probably faster way to access your input would be document.getElementById('myTextBox')
It is better to execute your product() function on form submit, rather than on button click event, since some users might want to just hit enter in the text field instead of the button, but then you would have to move it within the form boundaries and make it be type="submit"
MODIFIED CODE:
js:
<script>
function product(parameter1) {
a = parseInt(document.getElementById('myTextBox').value, 10);
var result = parameter1*a;
// alert(result);
return result;
};
</script>
html:
<form name='myForm' onsubmit="product(10); return false;">
Insert your number: <input id='myTextBox' value=''><br>
<input type='submit' value='CLICK HERE'>
</form>
You were calling method without argument. If you only want to retrieve value, below is the code. I dont know how ur going to use it
Insert your number:
<input type='button' value='CLICK HERE' onclick='product()'>
<script>
function product()
{
parameter1=10;
a=parseInt(document.myForm.myTextBox.value);
return parameter1*a;
}
</script>

Showing characters while typing

I need to see characters while I am typing characters inside an input, and I want to achieve this the simplest way. I have tried the following way, but it is not working. I am more interested to know what I am doing wrong rather than to get a script.
<input type='text' id='inpt' />
<script>
var getText = document.getElementById("inpt");
document.write(getText);
</script>
You're thinking of a callback, or event handler. Typically you would use onkeyup=callback_name(), and callback_name() would write to the element you want the output to appear in.
<script type="text/javascript">
function callback()
{
var text = document.getElementById('input').value;
document.getElementById('output').innerHTML = text;
}
</script>
<input type='text' id='input' onkeyup='callback()' />
<div id="output"></div>

Prefill field value and readonly

I have a form with several fields and I need to customize some fields using javascript for allow me to:
prefill the value "New York" for the field "city"
make the field "email" readonly
prefill AND make readonly the field "country"
To get the result of point 1, I used this code which works well:
<script type="text/javascript">function on_form_loaded(event) {
if (event=='reserve')
document.getElementById('city').setAttribute("value", "New York");
}</script>
For get the result of point 2, I used this code which works well:
<script type="text/javascript">function on_form_loaded(event) {
if (event=='reserve')
document.getElementById('email').readOnly=true;
}</script>
But now I don't see how to "mix" prefill/readonly paramters for get the result of point 3.
Someone can help ?
In addition I would like shorten the code for avoid to include a single javascript for each field. I make some test but without success. if you can give me some example...
I'm not sure what you're missing but try this
var country = document.getElementById('country');
country.value = "USA";
country.readOnly = true;
As jimjimmy1985 mentioned in the comments above, you can also do this in markup
<input name="country" id="country" value="USA" readonly>
Assuming You're using 'on...="on_form_loaded"' as attribute in the form tag and having no problem to add jQuery, You may try:
<script type="text/javascript">
jQuery('#ID_OF_YOUR_FORM').ready( function(event) {
if (event=='reserve') {
var form_object = jQuery(this);
form_object.find('#city').value('New York').end()
.find('#country').value('USA').end()
.find('#country, #email').attr('readonly', true);
}
});
</script>
Where ID_OF_YOUR_FORM has to be replaced by Your forms individual ID.

How to select value in input field with jquery?

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/

Categories