jQuery .val() method giving me the first entered value only - javascript

I am using the jQuery UI Dialog box to enter the URL of the Image. I am using the following method:
<input id="dlg" value="Open Dialog" type="button" />
<script type="text/javascript">
var img = '<div id="dialog" title="Insert Image" style="width:500px;height:300px">';
img += '<table><tr><td style="width:100px">';
img += 'Image URL: </td><td><input id="txt" type="text" value="" size="52" /></td>';
img += '</tr></table></div>';
$('#dlg').click(function(){
$(img).dialog({buttons: {'Ok':function(){
var value = $("#txt").val();
var http = value.substr(0,7);
alert(value);
$(this).dialog('close');
}}},
{ closeOnEscape:true, resizable:false, width:600, height:200
});
});
</script>
When I Press the (<input id="dlg" value="Open Dialog" type="button" />) button a dialog box appears, with a textbox input field. When I enter any value in the text field, It alerts that value. But when I Press the Button Second or Third time and Enter some other value in the textbox of the dialog, and press OK, it alerts the value that I entered for the first time. So, No matter How many times I click the button and enter any value, it will alert the value that I entered first time.
Am I getting the text box value var value = $("#txt").val(); correctly with this method?
If Yes, then Why it is giving me the first time entered value.
Note: I have cleared the cache of my browser so many times, so there is no chance of any cache problem.

Problem is each time you call it you are making a new copy of the dialog. That means you have multiple elements with the same name. To avoid that you need to destroy the dialog after you close it.
Change:
$(this).dialog('close');
To
$(this).dialog('close').dialog("destroy");
Other option is to create the element once and than reuse it.

It seems to me that the txt items are being created multiple times. You would need to remove the item from the DOM once you are done.
in this section
$(img).dialog({buttons: {'Ok':function(){
var value = $("#txt").val();
var http = value.substr(0,7);
alert(value);
// save value somewhere
$("#txt").remove();
$(this).dialog('close');
}}},

It is because you are creating the dom structure every time the dialog is created, so it is fetching the first created input box every time you request $("#txt").
So the solution is to remove the complete dom structure on close of the widget
$(img).dialog({
buttons: {
'Ok':function(){
var value = $("#txt").val();
var http = value.substr(0,7);
alert(value);
$(this).dialog('close');
}
},
close: function(){
$(this).remove()
},
closeOnEscape:true,
resizable:false,
width:600,
height:200
});

No matter How many times I click the button and enter any value, it will alert the value that I entered first time.
Am I getting the text box value var value = $("#txt").val(); correctly with this method?
Yes.
If Yes, then Why it is giving me the first time entered value.
Because $("#txt") refers to the first element in the DOM with that id. On each click, you dynamically create elements from your img string and append them to the DOM via the dialog widget. Yet, calling its close method only hides them, but does not remove them from the DOM so the click handler always extracts its value from the first created input.
Try calling the destroy method instead:
$(this).dialog('close').dialog("destroy"); // not sure whether the "close" is still necessary
Or you create the dialog only once, and open it on every click.

Related

Passing input to span field

I am trying to pass the input i have from an input to an span field. I use an api dropdown list with results. So if people click on an search result it get autofilled in (much like google). I want to pass this result to an span field I have in my page.
However I dont want an onclick event if people click on an result. Rather when people click out of the input field..
This is what I tried:
<div>
<input id="exercise-search" class="form-control" type="text" name="data">
</div>
<span id="namespan">Name</span>
And the simple script:
<script>
var name = document.getElementById("exercise-search").value;
document.getElementById("namespan").textContent=name;
function reload(){
var container = document.getElementById("namespan");
var content = container.innerHTML;
container.innerHTML= content;
}
</script>
However I still have to manually refresh the page to see the result. How can i automate this?
Add a listener for the change event to the input field. This will be executed when the user edits the field and clicks out of it.
document.getElementById("exercise-search").addEventListener("change", function() {
var name = this.value;
document.getElementById("namespan").textContent=name;
});

CRM 2013 field changes are not recognized in Custom Button JavaScript

I have a text field that should be filled before custom saving through HTML custom button.
When a user fills this field and tries to save through custom button, the text inside this field is null even if the user fills it.
Any suggestions Please?
Many Thanks for replying to my query. Actually, I am calling the below function from custom HTML button and I saw the result from alert message as NULL value until I leave the text box. Once I click some other Field then I am getting right value and saving the record successfully. I have posted my code below please have a look and suggest me how I can achieve it. So how to get the text value if a user doesn't leave the text box and click on the Save button?
function createRecord() {
var oDescription = Xrm.Page.getAttribute("new_description").getValue();
if (oDescription != null) {
var callentity = {};
var activityId;
var currentUserId = Xrm.Page.context.getUserId();
var oLeadId = Xrm.Page.getAttribute("new_lead").getValue()[0].id;
callentity.Subject = "Call Activity";
callentity.Description = oDescription ;
XrmSvcToolkit.createRecord({....Some more functions here...
})
}
HTML Button code for calling above function
<input id="SaveCall" onclick="parent.createRecord()" type="button" value="Save Phonecall"></p>
Xrm.Page.getAttribute(arg).getValue(val) won't return a value until focus is lost from the arg attribute (as you've found out).
Some options you could try:
document.getElementById('new_description_i')[0].value
Removing focus from "new_description" on click of your button.

JS - Holding DOM elements in variables

I need some clarification, as I have managed to confuse myself. Let's say we have the following code:
var textarea = document.getElementById("myTextarea");
var button = document.getElementById("myButton");
button.addEventListener("click", function() {
var words = textarea.value;
console.log(words);
}
This code runs by first gathering the DOM elements (the button and textarea) into their respective variables. Later in the code, when the button is pressed, textarea.value is placed into the variable words. Fair enough right?
My question is why isn't nothing logged into the console? The textarea variable is created and stored from the DOM after the page loads, which pressumably would be before the user had time to write anything into the textarea. This would mean that textarea.value should equal '' (nothing), as opposed to the string in the textarea at the time that the button was pressed by the user.
If anyone could clear this up for me that would be greatly appreciated.
Thanks :)
This would mean that textarea.value should equal '' (nothing), as opposed to the string in the textarea at the time that the button was pressed by the user.
Nope!
The value property of an input element updates dynamically based on user input or other code that changes it. It matters when you access the value property. Because you access it when the button is clicked, the value set on the element is read when the button is clicked.
If however you did something like this:
var textarea = document.getElementById("myTextarea");
var words = document.getElementById("myButton").value;
button.addEventListener("click", function() {
console.log(words);
}
Then the value would be read earlier (likely being blank, but could be a default value, and auto-save variable, or something else it was set to earlier), and changes by the user would be ignored.
Look at the 2 jsfiddles.
<input id = "myTextarea"/>
<button id= "myButton" type="submit"> test </button>
var textarea = document.getElementById("myTextarea");
var button = document.getElementById("myButton");
button.addEventListener("click", function() {
var words = textarea.value;
console.log(words);
});
In the first one, you are capturing the value of the text area inside the on click event. Thus, you get the value that has already been entered.
<input id = "myTextarea"/>
<button id= "myButton" type="submit"> test </button>
var textarea = document.getElementById("myTextarea");
var button = document.getElementById("myButton");
button.addEventListener("click", function() {
console.log(words);
});
In the second fiddle, you are capturing the value as soon as the DOM is loaded without waiting for the click event to happen. Thus, the value that prints in console is blank.
Thus, whether you will see the value entered or nothing at all depends on when you capture the value, after the event happens or right after the DOM is loaded. Hope this helps.

Html select not changes option on click after jquery instant filter in jsp

I have 3 select tags on one page, generated from struts2 select tag. I am using a jQuery filter function that filters the select. One textfield for every select, but all of them use the same filter function. I have another js function that is called on onChange event.
The problem is that before adding this jQuery function i was filtering the lists with form submit and reload the page and now the filtration happens instant, but when i write a filtration criteria the select somehow the select loses focus and when i click an element no select happens, or better lets say is a kind of select: the element is circled with a dotted line, not selected with a blue filled square. The js is called, the form submitted, but with the old value. However, if i first click in the select where are no elements (empty zone) and then i select an element everything is ok. How can i jump over the firs click?
And now my code:
I. The jQuery filter function and the binding to the selects and textfields.
jQuery.fn.filterByText = function(textbox) {
return this.each(function() {
var select = this;
var options = [];
$(select).find('option').each(function() {
options.push({value: $(this).val(), text: $(this).text()});
});
$(select).data('options', options);
$(textbox).bind('change keyup', function() {
var options = $(select).empty().scrollTop(0).data('options');
var search = $.trim($(this).val());
var regex = new RegExp(search,'gi');
$.each(options, function(i) {
var option = options[i];
if(option.text.match(regex) !== null) {
$(select).append($('<option>').text(option.text).val(option.value));
}
});
});
});
};
$(function() {
$('#selectedClientId').filterByText($('#filterClient'));
$('#selectedLocationId').filterByText($('#filterLocation'));
$('#selectedViewPointId').filterByText($('#filterViewpoint'));
});
II. One of the selects:
<s:select size="10" cssStyle="width:220px;"
label="Select a client"
listKey="id" listValue="name"
list="clientSelectList"
name="selectedClientId" id="selectedClientId"
headerKey="-1" headerValue="Client List"
onchange="onChangeSelect()"
/>
III. The select's textfield:
Filter:<s:textfield name="filterClient" id="filterClient" size="15" autocomplete="off"/>
IV. The onChangeSelect():
function onChangeSelect() {
document.getElementById('deviceListForm').action = '<s:url value="/admin/displayDeviceListPage.action"/>';
document.getElementById('deviceListForm').submit();
}
In the image: in the first select is how looks the selected option after jquery filter and in the other 2 selects are "the good" selected options.
http://i.stack.imgur.com/TAJeY.png
EDIT: So, after the first response to this post (Thanks Amit1992) I started digging further. In Mozilla after the first click (after the frame or dotted line appears) a request is made to the server with the old selected item (or null if none selected), the page refreshes as nothing happened.
In Chrome, on the other hand, the first click does not make any request. It just selects (let's say) the select tag. And the second select makes a good request.
Short story:
mozilla: click 1 -> request with old selected value ->refresh -> no changes
chrome: click 1 -> selects the select tag and no request is made -> click 2 -> request as it should happen
IE - works ok. 1 click-> select and load page as it should . OK this really surprises me. at first I thought is useless to look in IE what happens.
EDIT2
After some digging i concluded that the problem is that when typing in the textfield the select loses focus. If I put $('#selectedClientId').focus();
in the filterByText function at the end of the $(textbox).bind('change keyup', function() the fist select is focused after every char written. But this gives me another problem. I can't write more than 1 char at a time. I have to click the textfield, write a char, click again, write a char etc.
May be this will help you. i did some modification in your code.
$(function() {
$('#selectedClientId').filterByText($('#textbox'), false);
$("#selectedClientId").change(function(){
alert("you have selected ++ " + $(this).val());
});
});
I used change() event of jquery instead of javascript onChange().
you can refer this link http://jsfiddle.net/amitv1093/q55k97yc/ and I recommend you to use jquery fully if you are using it.
kindly let me know if it will work.
I solved the problem by changing the whole filter function. The function with problem was taken from a stack overflow question response (How to dynamic filter options of <select > with jQuery?). The problem is, from what I concluded, that the $(textbox).bind('change keyup', function() line was changing the focus on the textfield, so the first click was changing the focus to the select tag. The new function, the one that works was taken from the same post, John Magnolia's answer:
$(document).ready(function() {
filterClient();
filterLocation(); //same as filterClient
filterViewpoint(); //same as filterClient
});
function filterClient(){
var $this, filter,
$input = $('#filterClient'),
$options = $('#selectedClientId').find('option');
$input.keyup(function(){
filter = $(this).val();
$options.each(function(){
$this = $(this);
$this.removeAttr('selected');
if ($this.text().toLowerCase().indexOf(filter.toLowerCase()) != -1) {
$this.show();
} else {
$this.hide();
}
});
});
}

After AJAX callback, onblur goes back to original (or updated) field

I have an AJAX callback:
HTML:
<a onCLick="loadXMLDoc(id1,id2)">(Add)</a>
This calls an AJAX function that calls back a basic html input field in place of the above "(Add)"
onChange in this input field performs another AJAX callback that loads user input into a database.
What I am trying to do is once the field is filled out (or not filled out) and the field is blurred, it either goes back to the original or the newly updated value (but not any longer an input field).
I have searched around for a while and have come up with nothing. I am also new to javascript and AJAX. If it helps, I am using PHP mainly in this application.
Thanks
ADDITION
This is what I am trying to achieve:
The page lists different entries in table format.
There is a specific field that either has an id (stored in the database), or if field is null (in database) that field will display a button to add the id.
When pressed, the button calls a function which calls back an input field, the this replaces the previous "add" button. The AJAX callback places the input field in place of the "add" button.
This is where I need the help: After the user inputs the ID (or decides not to) and once the field no longer has focus, it changes from an input field back to what it was or the newly enter id. I am trying to do all this without refreshing the page.
I still don't follow exactly, but hopefully this will show you a means of creating/changing DOM elements in response to events like you've mentioned:
$(document).ready(function() {
$("#container").on("blur", ".name", function(e) {
var val = $(this).val();
if (!val) {
$(this).closest(".row").html("<button class='add'>Add</button>");
} else {
$(this).closest(".row").html("<span class='label'>Name: </span><span>" + val + "</span>");
}
});
$("#container").on("click", ".add", function(e) {
var html = "<span class='label'>New Name: </span><input class='name' type='text' />";
var row = $(this).closest(".row").html(html);
row.find("input").focus();
});
});
Working demo: http://jsfiddle.net/jfriend00/01ajd0y9/

Categories