How to use text input value with jquery get? - javascript

How do I use the value from a text input when using jquery get?
It works with the value from a select input, but for some reason the value from the text input doesnt get sent to the next page (updateName.php)
Here's the code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery-3.1.1.js"></script>
<script>
function updateName(){
$.get('updateName.php', {name : $( "#name" ).val()});
}
function updateGender(){
$.get('updateGender.php', {rego : $( "#gender" ).val()});
}
</script>
</head>
<body>
<input type="text" id="name" onchange="updateName()" size="10%">
<select id="gender" onchange="updateGender()">
<option value="1">Male</option>
<option value="2">Female</option>
</select>
</body>

Never mind.
The problem wasnt that the text wasnt being sent to the next page.
The problem was that on the next page I forgot to surround the value with apostrophes.
Like this:
$sql="UPDATE people SET name='$name' WHERE id=1";
The problem was it used to be like this:
$sql="UPDATE people SET name=$name WHERE id=1";

Related

Concatenate two fields and use this value to change/set value of a hidden field

Here is what I want to achieve. I have a requirement in which there is one dropdown for country codes and another input field for mobile number. I want to send country code and mobile input value as combined value so for that I am using a hidden field. When not using a hidden field it is easy to change value of a third tag element but that will not send value when form is submitted. So hidden field has to be used. So I have tried doing this but it is not changing value of hidden field.
<html>
<head>
<script language="javascript">
var dropdown = '';
var mobilenum = '';
function calldropdown()
{
dropdown = document.getElementById("country_code_id").value;
return dropdown;
}
function calltxtfield()
{
mobilenum = document.getElementById("mobileid").value;
return mobilenum;
}
function codemobile()
{
document.getElementById("codemobileid").value = calldropdown() + ' ' + calltxtfield;
alert(document.getElementById("codemobileid").value);
}
</script>
</head>
<body>
<form>
<select name="country_code" id="country_code_id" onchange="calldropdown()">
<option value="">Select</option>
<option value="+975">Bhutan</option>
<option value="+977">Nepal</option>
<option value="+94">Sri Lanka</option>
</select>
<input type="text" name="mobile" id="mobileid" onchange="calltxtfield()" />
<input type="hidden" name="codemobile" id="codemobileid" value="" />
<input type="submit" name="submit" value="Submit" onclick="return codemobile();" />
</form>
</body>
</html>
I can not explain it right now, but name="codemobile" seems to silently shadow function codemobile(). Rename one of the two and it works.
Also note that right now you are concatenating the function body (... + calltxtfield;), it should rather be ... + calltxtfield();

Uncaught TypeError: $(...).ready(...) is not a function even though it works on JsFiddle

The JSFiddle in question seems to have no trouble: http://jsfiddle.net/S3LF3/ (if you type a url like google.com it will select the value of ".com" or whatever you put after the dot and it is in the list)
However the jQuery function seems to be faulty?
In chrome I get this error:
Uncaught TypeError: $(...).ready(...) is not a function
Here is my code:
<html>
<head>
<title>Add Site</title>
<script src="js/jquery-3.1.1.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/msdropdown/dd.css" />
<script src="js/msdropdown/jquery.dd.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/msdropdown/flags.css" />
</head>
<body>
<h1>Add new site</h1>
<div class="contentbox">
<form method="post">
<input type="hidden" name="addsite" value="true"/>
<p>
<label for="site_url">Site url:</label>
<input type="text" name="site_url" id="urlText" placeholder="domain.xxx" value=""/>
</p>
<p>
<label for="site_url">Search locale:</label>
<select name="locale" id="locale">
<option value="">
Select locale
</option>
<optgroup label="Popular">
<option value=".dk" data-image="images/msdropdown/icons/blank.gif" data-imagecss="flag dk" data-title="Denmark">Denmark - Danish</option>
<option value=".de" data-image="images/msdropdown/icons/blank.gif" data-imagecss="flag de" data-title="Germany">Germany - German</option>
<option value=".au" data-image="images/msdropdown/icons/blank.gif" data-imagecss="flag au" data-title="Australia">Australia - English</option>
</optgroup>
</select>
</p>
<p>
<label for="site_url"></label>
<input type="submit" name="submit" class="btn" value="Add">
</p>
</form>
</div>
</body>
</html>
<script>
$(document).ready(function() {
$("#locale").msDropdown();
})
(function ($) {
$('#urlText').on('change', function () {
var value = this.value,
parts = this.value.split('.'),
str, $opt;
for (var i = 0; i < parts.length; i++) {
str = '.' + parts.slice(i).join('.');
$opt = $('#locale option[value="' + str + '"]');
if ($opt.length) {
$opt.prop('selected', true);
break;
}
}
})
})(jQuery);
</script>
What I want to do is when a user types a url, like "google.dk" , it should select the value with ".dk" at the end from the dropdown for him.
I played with your code and found out, it's the missing semicolon at the end of $(document).ready();
$(document).ready(function() {
$("#locale").msDropdown();
});
Just try it in the built-in editor:
<html>
<head>
<title>Add Site</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/msdropdown/dd.css" />
<script src="js/msdropdown/jquery.dd.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/msdropdown/flags.css" />
</head>
<body>
<h1>Add new site</h1>
<div class="contentbox">
<form method="post">
<input type="hidden" name="addsite" value="true"/>
<p>
<label for="site_url">Site url:</label>
<input type="text" name="site_url" id="urlText" placeholder="domain.xxx" value=""/>
</p>
<p>
<label for="site_url">Search locale:</label>
<select name="locale" id="locale">
<option value="">
Select locale
</option>
<optgroup label="Popular">
<option value=".dk" data-image="images/msdropdown/icons/blank.gif" data-imagecss="flag dk" data-title="Denmark">Denmark - Danish</option>
<option value=".de" data-image="images/msdropdown/icons/blank.gif" data-imagecss="flag de" data-title="Germany">Germany - German</option>
<option value=".au" data-image="images/msdropdown/icons/blank.gif" data-imagecss="flag au" data-title="Australia">Australia - English</option>
</optgroup>
</select>
</p>
<p>
<label for="site_url"></label>
<input type="submit" name="submit" class="btn" value="Add">
</p>
</form>
</div>
</body>
</html>
<script>
$(document).ready(function() {
//$("#locale").msDropdown();
});
(function ($) {
$('#urlText').on('change', function () {
var value = this.value,
parts = this.value.split('.'),
str, $opt;
for (var i = 0; i < parts.length; i++) {
str = '.' + parts.slice(i).join('.');
$opt = $('#locale option[value="' + str + '"]');
if ($opt.length) {
$opt.prop('selected', true);
break;
}
}
})
})(jQuery);
</script>
The reason the JSFiddle works fine is it doesn't actually use the country flag drop down menu plugin you found. The way the plugin works is different than the way a standard <select> html tag works.
I looked inside the jquery.dd.js file, and it seems there is no way to interact with the dropdown menu using javascript. Therefore, your line $opt.prop('selected', true); is valid for a real drop down menu (a <select> tag), but not for the plugin's drop down menu, which handles the selected state differently. Also, the plugin provides little documentation and has little to no comments in the code, so this makes it diffcult to know how the plugin works.
I can see 2 solutions to your problem:
You can try to understand the plugin's code in the jquery.dd.js file and try to implement a way to tell the plugin which element you want to select. I wouldn't normally recommend editing third-party plugins, but since the site you got the plugin from has not been updated since 2012, there is little chance for the plugin to receive updates in the future, so editing it would be safe in this case. It will require some knowledge in jQuery plugin making, though.
You can try to find another country flag drop down plugin that can be updated using javascript instead of using your mouse only. Such projects can be found on Github (here are some results found on Github: Country flag drop down menu results on Github).
Previous information found:
From the code you provided, you are missing a semi-colon after the call of the $(document).ready() function. It should look like this:
$(document).ready(function() {
$("#locale").msDropdown();
}); // <--- This semi-colon is missing
Also, the code in (function ($) {// code} )(jQuery); may be executed before the document was ready, which means this code could sometimes not work. Try putting this code inside your $(document).ready(); anonymous function. This way, you will be sure all html nodes will be accessible by jQuery.
Finally, you should consider putting your javascript logic somewhere inside the <html> tag (inside the <head>, right after <body> or right before </body>). While putting the <script> tag after the </html> tag may work at first, this is far from valid html and may be the cause of some problems you're having. The best way would be to put your javascript in a .js file and link it in your <head> the same way you linked jQuery and msdropdown:
<head>
<!-- Your other linked files... -->
<script src="js/main-logic.js"></script>
</head>
The JQuery shortcut - $() - seems to have been overridden by another library is my guess.
Try using:
jQuery( document ).ready(function( $ ) {
// Code that uses jQuery's $ can follow here.
});

Autofill data gets overwritten by onchange event of javascript

So I am facing a very annoying issue. I have a form with all empty field initially. Now user has a option to use default set of values by choosing a radio button 'yes' option.
If the user chooses to use default set of values then I fill all the form fields with default set of values using script. Everything goes fine till now.
The problem is my select drop-down not getting set with the default value. After debugging I found out that it is getting set but then On Change event of JS gets fired which is populating the drop down with the dataset from a ajax response.
How to stop on-change event to be fired if the user not clicked on the drop down and changed something.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<input type="radio" value="1" name="rdChoice"> Yes! Set Default Value
<input type="radio" value="0" name="rdChoice"> No! I have to fill data
<hr>
First Name : <input type="text" name="txtFirstName" id="txtFirstName"><br>
Last Name : <input type="text" name="txtLastName" id="txtLastName"><br>
Country :
<select onchange="getState()" id="selCountry">
<option>Choose</option>
<option>India</option>
<option>Japan</option>
<option>US</option>
</select>
</body>
</html>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function getState()
{
console.log("get state");
}
$(function()
{
$( 'input[name="rdChoice"]:radio' ).change(
function()
{
if(this.value==1)
{
$("#txtFirstName").val("Paresh");
$("#txtLastName").val("Gami");
$("#selCountry").val("India");
}
else
{
}
}
);
});
</script>
If user click on select box then and only getState is called.

Conditional form not working

I am new to javascript and I am trying to add a conditional field to a form. I have looked at these posts:
How do you create a hidden div that doesn't create a line break or horizontal space??
conditional display of html element forms
I have come up with this little example so far which works fine.
<html>
<head>
<script language="javascript">
function cucu(form){
if(form.check.checked){
document.getElementById("cucu").style.visibility="visible";
}
else{
document.getElementById("cucu").style.visibility="hidden";
}
}
function load()
{
document.getElementById("cucu").style.visibility="hidden";
}
</script>
</head>
<body onload="load()">
<form id="form">
<input type="checkbox" name="check" onclick="cucu(this.form)" >
<div id="cucu">
CUCU
</div>
</form>
</body>
<html>
I have tried the same method on a larger side and the only change is that the hidden element is a text field but it just doesnt' work.
This is the part of the form:
Album: <INPUT TYPE="checkbox" NAME="checkAlbum" onclick="checkAlbum(this.form)" id="idAlbum">
<div id="divAlbum" >
Choisir un album : <input type="text" name="Album" list="Albums">
<datalist id="Albums">
<?php
$requete = 'SELECT DISTINCT titreAlbum FROM Album';
$resultat = mysqli_query($connexion, $requete);
while($row = mysqli_fetch_assoc($resultat)){
echo '<option value="'.$row['titreAlbum'].'">';
}
?>
</datalist> <br><br>
</div>
My head looks as follows:
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html ; charset=UTF-8" />
<title>BLABLA</title>
<link rel="stylesheet" type="text/css" href="include/styles.css">
<script language="javascript" >
function hideElements(){
document.getElementById("divAlbum").style.visibility="hidden";
}
function checkAlbum(form){
if(form.checkAlbum.checked){
document.getElementById("divAlbum").style.visibility="visible";
}else{
document.getElementById("divAlbum").style.visibility="hidden";
}
}
</script>
</head>
I really don't know what the problem is. I've checked the functions again and again. Any suggestions for the possible error? Thanks
The reason your button is not working is that this refers to the clicked input itself. The form property on the input refers to the value of the form attribute, not the actual form. In reality you don't need the form attribute, you can simply use this.checked to see if the corresponding input is currently checked.
Album: <INPUT TYPE="checkbox" NAME="checkAlbum" onclick="checkAlbum(this)" id="idAlbum">
function checkAlbum(cb){
if(cb.checked){
document.getElementById("divAlbum").style.visibility="visible";
}else{
document.getElementById("divAlbum").style.visibility="hidden";
}
}
Beyond this I would suggest that you consider not applying your JavaScript inline. Keeping your code separate from your mark up improves readability and can help prevent errors. You might consider using the jQuery framework as it will make this sort of thing much easier.
$(function(){
$('#idAlbum').on('change', function() {
// use change instead of click in case there's a label involved
$('#divAlbum').toggle(this.checked);
});
});

how display a jquery validate message inside a div tag

I am successfully validating a required field using jQuery Validate method. Everything works fine but I want to display the error message inside ia div tag which an option to make the error disappear after 10 or 20 sec of showing it, basically like a auto hide.
here is the markup I have created
<script type="text/javascript">
$(document).ready(function(){
$("#cForm").validate({
rules: {
PaymentMethod: {
required: true
}
,ShippingMethod: {
required: true
}
},
messages: {
PaymentMethod: {
required:" Select a payment method!"
}
,ShippingMethod: " Select a shipping method!."
}
});
});
</script>
<sytle="text/css">
#ship-msg, #pay-msg {display:none; background:url("/image/req.gi") no-repeat left center transparent;}
.msg { color:#000;}
</style>
<form id="cForm" method="post" action="/pay.html">
<div class="ship-options">
<label for="ShippingMethod">Shipping Method</label>
<select id="ShippingMethod" name="ShippingMethod" >
<option value="">Choose Shipping Method</option>
<option value"UPS-GROUND">UPS GROUND</option>
<option value"UPS-1DAY">UPS 1DAY</option>
<option value"UPS-2DAY">UPS 2DAY</option>
</select>
<div id="ship-msg><div class="msg"> // display the error messgae here </div>
</div>
<div class="pay-options">
<label for="PaymentMethod">Payment Method</label>
<select id="PaymentMethod" name="PaymentMethod" >
<option value="">Choose Paymenet Method</option>
<option value"VISA">VISA</option>
<option value"MASTERCARD">MASTERCARD</option>
<option value"AMEX">AMERICAN EXPRESS</option>
</select>
<div id="pay-msg><div class="msg"> // display the error messgae here </div>
</div>
<input type="submit" value="Continue" id=" />
</form>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.8/jquery.validate.min.js"></script>
and so when some clicks the continue button and if the methods are not selected display them display the respective divs and its message
I know i am missing something
Thanks and appreciate it
You misspelled the opening <style> tag. Therefore #ship-msg, #pay-msg won't be hidden:
<sytle="text/css"> ... </style>
Your script must be placed after jQuery has been loaded. That is at the end of your document. If you place it before the jQuery script is loaded, the browser won't recognize function calls like $(document).ready() and $("#cForm").validate().
I am assuming that the obvious mistakes (jQuery reference BEFORE the code and style tag mispelling) were simple oversights on your part and that you want to know how to make the appearing/disappearing happen. If you want to make the error appear and then go away after some time, when the validation fails call this function:
function ToggleErrorMessage(messageDiv) {
messageDiv.toggle().delay(20000).toggle();
}
Which will turn the div on, wait 20 secs, and then turn it off. "messageDiv" is the div which you want to apply this to.
This isn't strictly using your validate but this should help you on your way
example

Categories