How to get modified text from input JQuery or javascript - 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 });

Related

Need to check value of hidden input field related to clicked element (multiple with same name)

Title isn't that clear, so let me see if I can explain what I'm doing.
I'm listing off users' posts, and have a like/comment button with those posts.
What I need to do, is capture when the like button is clicked (<span> tags), and then grab the post id from the hidden input field, and use that to post to the PHP script.
The PHP is doing all of the checking for if they're friends, privacy level is correct, etc. before actually submitting the like to the database, but I am currently just having the javascript/jquery be generated when the post is shown (naming each js variable/DOM element according to post id), but that's not very efficient and looks messy when viewing the source (But, it's the only way I can get it to work).
I want to be able to use an external javascript file to check when just the like button is clicked, and know what post that is being liked, and work that way.
I've been looking into this for quite some time, and it's to my understanding that this might work, but I have had no luck. I'm generating multiple posts on one page using foreach() loop, so the names/ids/classes of the elements are the same.
For a little better understanding, here's an example of what a post might look like:
<div class="feedPost">
<img src="#" class="feedProfile"/>
FirstName LastName
<div class="feedPostBody">Hello, world!</div>
<input type="hidden" value="24772" name="feedPostID">
<span class="feedLikeButton">Like</span> | Comment | 2 mins ago
</div>
and, using javascript/jquery, I want to be able to do something like this in an external js file:
$('.feedLikeButton').on('click',function(){
var post_id = 0; //I need to get the ID from the post that the like button is related to.
//If I just did $('.feedPostID').val() it wouldn't work
$.post("https://mysite/path/to/like.php", {post: post_id}).done(function(data){
if(data == "success"){
//This will set text from "Like" to "Unlike"
//Again, I can't just do $('.feedLikeButton') to access
//I guess I could do this.innerHTML? Would still need to access feed post id
} else {
//Probably will just flash error to user if error, or something similar
}
});
});
You should get the like button
var likeButton = $(this);
Then get it's container
var container = likeButton.parent();
Then find the hidden field
var idInput = container.find('[name="feedPostID"]');
Then get it's value:
var id = idInput.val();
With all these references you can do whatever you want.

Form doesn't serialize after Ajax insertion

Tearing my hair out over this. I have a 40 rows of simple forms that are being generated dynamically from a mysql database. Each form has a unique ID based on the database ID. After clicking submit the results get updated in the database and inserted into the div (#result).
Works the first time perfectly. However after the first time the script won't serialize the updated form data. The ID is fine (checked via alert) but the formData is empty (also checked via alert).
Thinking I need to re-target the form somehow? Any help would be greatly appreciated. Thanks.
$('#result').on('click', '.submitform', function () {
var id = $(this).attr('id');
var formData = $('#'+id+'-form').serialize();
$.ajax({
type: "POST",
url: "ajax-process-form.php",
data: formData,
cache: false,
success: function(server_response){
$("#result").html(server_response).show();
}
});
return false;
});
Just reasoning... I might be wrong...
This code
$('#result').on('click', '.submitform'
binds to the click event on result and filters .submitform, then executes with this being the .submitform
when the success comes from the server, you are rewriting #result
$("#result").html(server_response)
if server_response does not contain a .submitform then next calls to the first onclick event will not execute because .submitform does not exist anymore inside #result
If this is the error, then to solve, use another div to show the result instead of #result or bind click to another separated, not contained within div
Arrgh - it was the structure after all. Although it worked the first time the table structure prevented it from working a second time. I have no idea why ... but there you go. Thanks for the help!

How to sanitize X-Editable value *before* editing?

I'm using X-Editable to give users the possibility to edit values inline. This works great, but I now want to use it for some money values which are localized in a "European way" (e.g.: € 12.000.000,00). When I click edit, I want the input to only contain 12000000 though.
Is there a way that I can sanitize the value in X-editable before it gets displayed in the X-Editable input? All tips are welcome!
See the plunker http://plnkr.co/edit/Vu78gRmlKzxrAGwCFy0b. From X-editable documentation it is evident you can use value property of configuration to format the value you want to send to the editor as shown below.
Element displaying money value in your HTML:
12.000.000,00
Javascript code in your HTML:
<script type="text/javascript">
$(document).ready(function() {
$.fn.editable.defaults.mode = 'inline';
$('#money').editable({
type: 'text',
pk: 1, //Whatever is pk of the data
url: '/post', //Post URL
title: 'Enter money', //The title you want to display when editing
value:function(input) {
return $('#money').text().replace(/\./g, '').replace(/,00$/,'');
}
});
});
</script>
If you want to format the value back for display after editing you can do that in display property of the configuration hash like this:
$('#money').editable({
type: 'text',
pk: 1, //Whatever is pk of the data
url: '/post', //Post URL
title: 'Enter money', //The title you want to display when editing
value:function() {
return $('#money').text().replace(/\./g, '').replace(/,00$/,'');
},
display:function(value) {
//var formattedValue = formatTheValueAsYouWant(value);
//$('#money').text(formattedValue);
}
});
Seems like there is no callback function available for what you want.
so You need to make it outside of the library.
here is how to do it.
$(document).on("focus",".form-control.input-sm",function(){
//remove all characters but numbers
var _val = $(this).val().match(/\d/g).join("");
//set it.
$(this).val(_val);
});
replace the part of .form-control.input-sm into your case.
I just tested this on the library's demo site's first demo fieled named "Simple text field" with chrome developper tools
http://vitalets.github.io/x-editable/demo-bs3.html
Since x-editable form would be generated right before showing up.You need to hook an event to document and wait for input field inside of x-editable form gets focus which is the time x-editable shows up and edit the value into whatever you want.
and Yes, This method works AFTER the input field shows up but It's hardly possible to notice that value is changing after it gets displayed.

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?

Populating JScript Array for reuse on SELECTs

Forgive me if this is already 'somewhere' on StackOverflow, but I don't 100% know exactly what it would come under...
I'm trying to retrieve information from a WebService, store this in an array, and then for each <select> within my ASP.Net Datalist, populate it with the array AND have binding attached to an OnChange event.
In other words, I have an array which contains "Yes, No, Maybe"
I've an ASP.Net Datalist with ten items, therefore I'd have 10 <Select>s each one having "Yes, No, Maybe" as a selectable item.
When the user changes one of those <Select>s, an event is fired for me to write back to the database.
I know I can use the [ID=^ but don't know how to:
a) Get the page to populate the <Select> as it's created with the array
b) Assign a Change function per <Select> so I can write back (the writing back I can do easy, it's just binding the event).
Any thoughts on this?
I have built a simple example that demonstrates, I think, what you are attempting to accomplish. I don't have an ASP.Net server for building examples, so I have instead used Yahoo's YQL to simulate the remote datasource you would be getting from your server.
Example page => http://mikegrace.s3.amazonaws.com/forums/stack-overflow/example-multiple-selects-from-datasource.html
Example steps:
query datasource to get array of select questions
build HTML of selects
append HTML to page
attach change event listener to selects
on select value change submit value
Example jQuery:
// get list of questions
$.ajax({
url: url,
dataType: "jsonp",
success: function(data) {
// build string of HTML of selects to append to page
var selectHtml = "";
$(data.query.results.p).each(function(index, element) {
selectHtml += '<select class="auto" name="question'+index+'"><option value="Yes">Yes</option><option value="No">No</option><option value="Maybe">Maybe</option></select> '+element+'<br/>';
});
// append HTML to page
$(document.body).append(selectHtml);
// bind change event to submit data
$("select.auto").change(function() {
var name = $(this).attr("name");
var val = $(this).val();
// replace the following with real submit code
$(document.body).append("<p>Submitting "+name+" with value of "+val+"</p>");
});
}
});
Example datasource => http://mikegrace.s3.amazonaws.com/forums/stack-overflow/example-multiple-selects-from-datasource-datasource.html
Example loaded:
Example select value changed:

Categories

Resources