Updating an html "value" with a jquery variable - javascript

So i'm building a messaging application in which a user clicks on a button, a jquery prompt is displayed asking for the user to type in their message, and then ideally the message is sent using a separate ajax function.
Here is the code in question:
jQuery message prompt function:
function getInput() {
var text = prompt("Enter message", "");
if (text != null) {
document.getElementById("demo").innerHTML = text; //failed attempt at updating the value just using the id of the input.
}
}
HTML:
<form name="messagesend" method="post" onsubmit="return sendMessage(this);">
<input type="hidden" id="demo" name="message" value="I want to update this field with the result of the javascript text variable" />
<input type="hidden" name="regId" value="<?php echo $row["gcm_regid"] ?>"/>
<input type="submit" class="send_btn" value="Volume-Vibrate" onclick="getInput()"/>
</form>
As you can see, the field I want to update is the string contained in value which is the message being sent. How could I get that to update with the result of whatever the user puts in the text prompt?
Any help would be greatly appreciated!
EDIT:
Updated jQuery function to the following:
function getInput() {
var text = prompt("Enter message", "");
if (text != null) {
$("#demo").val(text);
}
}
This may be a different question, but when the button that is created in the HTML I originally posted is clicked, it displays the prompt and I type in a message, but the default value that I placed is still the message being sent. Is
onsubmit="return sendMessage(this);"
Being executed before the jQuery is updating the value field? And if so, is there anyway to fix that?
If it helps, here is sendMessage which uses ajax to send off the message to a php script.
The HTML value field (which I'm trying to get to be the user-input string from the jQuery prompt using getInput()) becomes the data variable, which also contains the registration id of the designated recipient of the message.
function sendMessage(formObj){
var data = $(formObj).serialize();
$(formObj).unbind('submit');
$.ajax({
url: "send_message.php",
type: 'GET',
data: data,
beforeSend: function() {
},
success: function(data, textStatus, xhr) {
$('.txt_message').val("");
},
error: function(xhr, textStatus, errorThrown) {
}
});
return false;
}

A HTML field doesn't have inner HTML (the tag is self-closing), it has a value (and a value property).
But as you're using jQuery, you should use its functions anyway: $("#demo").val(text)

As #Lucas has mentioned, $("#demo").val(text) works (see the JQuery documentation)
Another way of doing the same thing (referencing the input field by name):
$('input[name="demo"]').val()
However, a name does not need to be unique, while an id should be unique (see this SO answer). It would be safer to add id="demo" to your input name - overkill in this case, but good practice.

Related

Client side data to server side

I'm trying to use a JavaScript popup box (prompt) to get some user input on my website, and then do some more actions on the server-side based on what the user does.
The popup box is, for lack of words, popping up.
The following is the code that I have tried to use for this:
<div>
<asp:HiddenField ID="hidden" runat="server" />
</div>
<script>
function userInput() {
var reason = prompt("Enter reason for deleting:", "");
//User pressed okay but didn't type anything
while (reason == "") {
//Keeps cycling until reason given or cancel is hit
reason = prompt("Enter reason for deleting:", "");
}
if (reason != "" && reason != "Code:CancelDelete") {
//User typed something and hit okay
document.getElementById('hidden').innerHTML = reason.toString();
$('#deleteReason').val(reason.toString());
$("#hidden").val(reason.toString());
}
else {
//User hits cancel
document.getElementById('hidden').nodeValue = "Code:CancelDelete";
}
}
</script>
The while loop in the script works for what I need it to do. The problem from what I can tell is trying to set the value of the HiddenField. I have tried the following ways:
innerHTML
innerText
nodeValue
While looking into this, I have seen .value used a lot and have tried it myself but when I go to type document.getElementById('hidden').value =, there is no popup option or description for .value.
I have tested the server side code and so I know that works. It all comes down to getting the user input. Either way, here is an excerpt from the c# code:
string deleteReason = hidden.Value;
//string deleteReason = test.InnerHtml.ToString();
if (deleteReason.Equals("Code:CancelDelete"))
{
}
else if (!deleteReason.Equals("Code:CancelDelete") && !deleteReason.Equals(""))
{
More or less at a loss on this one.
Update 1:
Here is the html code generated on the client side browser(Firefox) for the hidden field:
<input name="ctl00$IndividualPageContent$hidden"
id="IndividualPageContent_hidden" type="hidden">
When you type an element ID on webform, the asp.net gives it a unique ID based on some things (Your form, your repeater, etc...)
If you want to use jQuery with this ID, you can use the ClientId prop.
Something like this:
if (reason != "" && reason != "Code:CancelDelete") {
//If your server id= "hidden"
ele = $("#<%= hidden.ClientID %>");
ele.html() = reason.toString();
...
}
Another option is to add the static ID to your server element, and then your code will work as is. (the html will be rendered with ID = hidden)
ClientIDMode="static"
<div>
<asp:HiddenField ID="hidden" runat="server" ClientIDMode="static"/>
</div>
You are trying to set the value of an element with id 'hidden', but that's not the id of your hidden input.
The correct id is 'IndividualPageContent_hidden'.
Set the value like this instead:
document.getElementById('IndividualPageContent_hidden').value = 'Your value here';

How to get modified text from input JQuery or javascript

I'm having a problem getting modified text from input. The input is loaded with some text I get from a database and with an option i should take the onlyread attr off and change the values. Thats ok but when i click on the save button after writing something else in the inputs, it gets the old values with .val(). How can i get the new ones?
The code is something like this.
var anInput = $("#anInput").val(); //gets old value
var otherInput = $("#otherInput").val(); //gets old value
$.ajax({
type: "POST",
dataType: "html",
success: doSomething,
timeout: 4000,
error: someProblems,
url: "modules/mod.php",
data: {anInput: anInput, otherInput: otherInput}
});
I added the AJAX code just to mention that i need the values to do something. AJAX is working.
I know this can be done with a form but that will reload the page and I don't want that.
Sorry for my rusty English and thanks :)
EDIT: Perhaps I'm not correctly speaking when saying "change the values" what I'm doing is selecting the text and writing something else.
I show some information with the inputs, click a button that allows me to modify, type some new text in the inputs and then click "save"
HTML is genereted by another AJAX
<div class="infoVideo">
<input id="anInput" value="someTextFromDataBase">
<input id="otherInput" value="someTextFromDataBase">
<input type="button" id="btnMod">
<input type="button" id="btnSave">
</div>
If I erase and type something else in the input .val() is getting old someTextFromDataBase
Edit: As per a guess in my comments, there was more than one #anInput in the page so the code was only retrieving the value from the first one which was not the one being edited. The solution is to not have any duplicate id values in the HTML of the page.
I suspect that your code isn't really like you show. You are probably doing these:
var anInput = $("#anInput").val(); //gets old value
var otherInput = $("#otherInput").val(); //gets old value
only once and then trying to use anInput and otherInput much later when the form fields have already changed. You can get the current values by not caching those and just retrieving the current values when you need them by changing this:
data: {anInput: anInput, otherInput: otherInput}
to this:
data: {anInput: $("#anInput").val(), otherInput: $("#otherInput").val()}
That way, you are always retrieving the latest and greatest values right before your Ajax call.
Please confirm format of data returned by mod.php. The AJAX block is expecting to receive HTML formatted text dataType: 'html', -- but you are sending json, so is that what you are expecting back?
If this note doesn't reveal the solution, then please show us your doSomething function - that's where the returned data is handled.
Probably you've tried this already, but what happens if you do this:
var anInput = $("#anInput").val(); //gets old value
alert(anInput);
var otherInput = $("#otherInput").val(); //gets old value
alert(otherInput);
$.ajax({ //etc });

Send Input box value in ajax call

I want to send my input box value in my ajax call.
I am trying but not work.
My Input box
<form>
<input type="text" onkeydown="filter()" id="searchTxt" placeholder="Filter" value="" >
</form>
My Javascript code
function filter()
{
filterText = $('#searchTxt').val();
$( ".pagination" ).html(totalOutput);
$.ajax({
type: "POST",
url: ""+baseUrl+"userList4",
data: { searchText: filterText},
success: function(msg) {
$(".paginateData").html(msg);
}
});
}
Here filterText = $('#searchTxt').val(); always get null
The code to get the value is correct. So, I would say there is another issue here outside of the code you have shared. It could be jquery can't find that field. Try outputting the length to make sure jquery has actually found that text box.
var textBox = $('#searchTxt');
console.log(textBox.length);
You could also just pass 'this' to the method and not have to use jquery at all, which I would suggest.
Another issue could be that the onekeydown is getting called before the text has even reached the textbox. So at the time the value would be null. But I would assume you tested with more than one keystroke?

Form onsubmit() does not function

I want to control my form for the required input texts, and I have made a function in javascript. But when I click the button, and I havent fill the required field nothing the message do not appear, and I can go to the other page.
the function is:
function Validate(){
// create array containing textbox elements
var inputs = [document.getElementById('firstname1')];
var error;
for(var i = 0; i<inputs.length; i++)
// loop through each element to see if value is empty
{
if(inputs[i].value == '')
{
error = 'Please complete all fields.';
alert(error);
return false;
}
}
}
and the part of form is:
<form name="password" onsubmit="return Validate()" method="post" id="password" action="#">
<input type="submit" value="Proceed" id="submit1" onclick="displayform2()" class="button" style=" margin-top: -40px;margin-left: 60%;width: 25%" disabled>
I have noticethat if I put off the onclick method in the button it works, but I should have this method at the button...How can I solve this?Please help me
function displayform2() {
/*For desktop*/
if (document.getElementById('desktop1').style.display=='block') {
document.getElementById('desktop1').style.display='none';
document.getElementById('desktop2').style.display='block';
document.getElementById('desktop3').style.display='none';
}
/*For mobile*/
if (document.getElementById('mobile1').style.display=='block') {
document.getElementById('mobile1').style.display='none';
document.getElementById('mobile2').style.display='block';
document.getElementById('mobile3').style.display='none';
}}
It opens another form in the page...so when I click the button the first form dissapeared and the second form is displayed
You have this: var inputs = [document.getElementById('firstname1')];
Then you try to loop through that. I'm betting firstname1 is a field, so it's either null (if that field doesn't exist) or an array with only one element (the field). It looks like you are trying to check all required fields, so that won't work.
I'm not 100% what you ultimately want to do, but it will likely be much easier if you use a framework like jQuery; otherwise, you are going to have to do some complicated case-handling for different browsers.
Nowhere in your code do you call submit. That is why the function in the onsubmit handler is not triggered. If you want the button to submit the form, it would need to be a submit button.
Your example is a little unclear. For example, you are trying to validate whether a value has been entered into the input "firstname1", but you don't have markup for that element in your HTML.
I suspect what you are trying to do is to validate whether the form has been filled out or not. Something like the following (which validates input "firstname1") will do the job:
$(document).on("click", "#submit1", function(){
if($("#firstname1").val() == "" || $("#firstname1").val() == null){
alert("Please complete all fields.");
}
});
Working example here
The above requires jQuery, but can also be converted into vanilla JavaScript.
Load the jQuery library in the "head" section of your document by including the following code:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

Specific pop up with ajax and query from database

I use in a form a simple radio button with "YES" or "No", I wish that when I click yes a pop-up window will be automatically shown with this specific message:
Are you sure you want to sell a new membership to [User’s Full Real Name from database] with the number [ number of product from database ] ?
That means at the same time an ajax query will be established to return the name of user and the number of product from database.
I'm not very good in JS/Ajax, can anyone help me with this?
Edit :
I know to do what you wrote in the message bellow,what I'm not sure is how to run the pop-up window automatically when I choose "yes" radio button?
To use ajax, you first need to create a server-side function that does what you need. For instance, a php script that takes a userID and returns the user's full name. Let's suppose you create that script and call it "username.php".
On your page, you'll use a javascript function, such as the jquery .ajax function to send an asynchronous request to username.php. The function call will look something like this:
function lookupUsername(){
$.ajax({
type: "POST",
url: "username.php",
data: { ID: $("#userID").val() }
}).done(function( msg ) {
alert( "Username: " + msg );
});
}
In the above example, I've assumed that the user ID is embedded somewhere on your page in an element with ID="userID". The term $("#userID").val() is a jQuery function that looks up the value of the HTML element called "userID".
Next, you need to call the lookup function when the yes radio button is clicked. So something like:
<input type="radio" name="foo" id="foo" value="yes" onclick="lookupUsername()" />
Note that to use the JQuery framework (The .ajax() function and the $() selector function, you need to include the JQuery framework on your page:
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
It's totally possible to do an ajax call without jQuery, but the code is a little messier.

Categories

Resources