I am trying to make an autocomplete suggestion for countries listed in my database. I managed to get the list and I am trying to bind click event for entries for each country. Although I believe this is the way to do it, code is always using the last item's value and placing it to the input field.
Suggestions is my autocomplete container and the text field that I want to update is the box.
$('#box').on('input', function (){
var typedLocation = { 'location' : $(this).val() };
var key;
$.post( "/suggestions.php", typedLocation, function( data ) {
$('#Suggestions').html('').show();
for (key in data) {
$('#Suggestions').append('<div id="suggest' + key + '" >' + data[key] + '</div>');
$('#Suggestions').find('#suggest' + key).click(function (){
$('#Suggestions').hide();
$('#box').val(data[key]);
});
}
});
});
Instead of using the variable for setting the value of input field, I have used $(this).html() in the click function.
Adopting it to Joe's example (as it seems more elegant):
var $elem = $('<div>' + data[key] + '</div>');
$elem.click(function () {
$('#Suggestions').hide();
$('#box').val($(this).html());
});
$('#Suggestions').append($elem);
Related
So I have multiple delete buttons on a table and each button has there own unique id. I am trying to get this value via javascript but I can't get it to work at all.
Here is a section js that is working properly and loads the correct html (this is ran for each movie):
function createRow(movie) {
movie.NewDate = new Date(movie.ReleaseDate);
return '<tr><td><img class="movieImage" src="' +
movie.ImageLink +
'" alt="' +
movie.Title +
' Image" style="width:50px;height:75px">' +
'<td>' +
movie.Title +
'</td><td>' +
movie.NewDate.toLocaleDateString("en-US") +
'</td><td><button type="button" class="removeButton" value="' + movie.DVDID + '">Delete</button></td></tr>';
}
And here is the js where I am trying to retrieve the id:
$(document)
.ready(function () {
var deleteButtons = $(".removeButton");
deleteButtons.each(function (index) {
var currentButton = $(this);
var buttonValue = currentButton.val();
currentButton.click(function () {
alert(buttonValue);
});
});
});
I found the last snippet via Click one of multiple buttons, put value in text input
Right now just getting a proper alert would be sufficient.
Have you tried this approach:
$("#tableId").on("click", ".removeButton", function(){ alert($(this).attr("value")); })
This "on" binds all the ".removeButton" elements with the given function when click is triggered.
Your javascript should look like this:
$(document).ready(function () {
var deleteButtons = $(".removeButton");
deleteButtons.on('click', function() {
alert($(this).attr('value'));
});
});
Also, since you adding these buttons dynamicly with javascript, you may need to rebind button click events after you add new row. Also binding should be done after loading button html to DOM.
Since you are creating buttons dynamically, you won't be able to reach them properly because when the javascript was initiated they didn't exist in the DOM. So in order for you to be able to find the buttons, you'll have to look at the document scope and then find which button (class) you click on, like so:
$(document).on('click', '.removeButton', function(){
console.log($(this).val())
})
See fiddle for complete example
I use semantic UI dropdown plugin. active the plugin on load by
$(function () {
$('select.dropdown').dropdown();
});
in my code there is two dropdown one's date is dependen on other. on change first dropdown I populate other's value.
$('.city').on('change', function () {
var id = $(this).val();
if (id != '') {
$.get('ajax/town/' + id).done(function (result) {
var div = '';
$.each(result, function (i, e) {
div += '<option value="' + e.id + '">' + e.town + '</option>';
});
$('.town').html(div);
$('select.dropdown.town').dropdown('refresh');
});
}
});
But the dropdown doesnot reinitialize, but show a list in a div. How to solve this issue.
The problem solved. by changing...
$('.town').html(div);
$('select.dropdown.town').dropdown('refresh');
to
$('.town select').html(div).dropdown();
I am doing an attach files project where I need to auto check a file name when there is only one file to be chosen to attach. It is easy to auto check it as a checkbox, but when it is checked, there is an onclick function called to update the file in the server side.
Since the <input> tag is dynamically added based on the number of required attaching files, .trigger('click') didn't work on it.
$.each(speedLetterArray, function (key, value) {
var idLine = fileId + '_b' + value.reasonCode;
var idContainer = 'sliC_f' + idLine;
var idItem = 'sli_f' + idLine;
output.push('<div style="' + cssDisplay + '" class="sliContainer" id="' + idContainer + '">');
//auto checked if only one item
if (fileCount == speedLetterArray.length) {
value.isSelected = 'true';
}
if (value.isSelected == 'true') {
output.push('<input id="' + idItem + '" onclick="updateSpeedLetterItemLists(this);" type="checkbox" name="' + idItem + '" value="' + value.reasonCode + '" class="testClass" style="margin:0px;" />');
} else {
//some code here
}
}
I used checked=checked to auto check the file, but couldn't trigger the onclick function updateSpeedLetterItemLists(this) to update the files on server side.
which works fine when I manually click it.
I tried $(.sliContainer).find('input:checkbox:first').trigger('click'); after the <input> tag or in $(document).ready, either of them works.
I thought maybe I didn't find the right object since when I use alert($(.sliContainer).find('input:checkbox:first').val()) I get "undefined" value.
You could do
$('yourelemtid').click()
Or since it is dynamically added
$( "yourelemtid" ).live( "click", function() {
});
Since the element is added after the initial javascript initialization it won't see your new elements to add the hooks onto.
jQuery Doc for .live
.live is deprecated, use this:
$(document).on( "click", "#yourelemtid", function() {
...
});
I have two selects that both have use a function to add elements to the other select.
Here's what I have:
$("#lecturers option").dblclick(function ()
{
var element = $("#lecturers option:selected");
var value = element.val();
element.remove();
var values = value.split(";")
$("#selected_lecturers").append('<option value="' + value + '">' + values[2] + ', ' + values[1] + '</option>');
});
and vice versa:
http://jsfiddle.net/VJAJB/
It somehow only works once, and the newly added elements don't trigger the function.
Any idea on how to fix this?
The issue is how you bind the dblclick function to the elements. The current selector only returns the option elements you have in your select element at the time of binding. To alter this, you can use delegated events.
$('#lecturers').on('dblclick', 'option', function() {
//Do stuff here
});
This makes sure that any option element you add to the select element will trigger this event when it is double clicked.
Here is an updated fiddle: http://jsfiddle.net/VJAJB/4/
Please note that other users have given you solutions that will work. However, best practice is to limit the number of events bound to the document itself. Whenever possible, you should bind delegated event listeners to the nearest non changing element.
This happens because the handler doesn't get bound to the new elements. You can do it like this, which will bind it to a descendant (in this case body) and specify the selector it will be applied to:
$('body').on('dblclick', '#lecturers option', function ()
{
var element = $("#lecturers option:selected");
var value = element.val();
element.remove();
var values = value.split(";")
$("#selected_lecturers").append('<option value="' + value + '">' + values[2] + ', ' + values[1] + '</option>');
});
$('body').on('dblclick', '#selected_lecturers option', function ()
{
var element = $("#selected_lecturers option:selected");
var value = element.val();
element.remove();
var values = value.split(";")
$("#lecturers").append('<option value="' + value + '">' + values[2] + ', ' + values[1] + '</option>');
});
If both have a parent/descendant element that is present at the time of binding, you can use that instead of 'body' to improve performance.
Fiddle: http://jsfiddle.net/VJAJB/2/
You need to use on method instead. In latest jQuery versions is:
$( document ).on( "dblclick", "#lecturers option", function ()
Updated jsFiddle
I’m trying to make a modal dialog with images where you can select multiple images. I need to get values from an input and then to empty it, but I cannot empty the input. I tried .val('') and .val(null), but neither worked for me.
Here is the full code:
$("#hdselect").click(function(){
$(".modal").html("");
$.post('mediaservice.php',{hd:'ok',images:$("#hdimages").val()},function(data){
$(".modal").append(data);
});
$(".modal").dialog({
'modal':true,
'title':"Click the image to select",
'width':960,
'height':600,
'resizable':false,
'show': {effect: 'drop', direction: "up"},
'buttons': {"Ok": function() {
var hd=Array();
var hdval=$("#hdimages").val();
$("#hdimages").attr('value',' ');
$("input[name='hd[]']:checked").each(function(){
hd.push($(this).val());
});
if(hdval!=''){
hdval=hdval+","+hd;
}else{
hdval=hd;
}
$("#hdimages").val(hdval);
var images=$("#hdimages").val();
$.post('mediaservice.php',{getHd:images},function(data){
$("#imgthumbBase").append(data);
});
$(this).dialog("close");
}
}
});
});
The idea is that the user clicks a button and a modal dialog opens with multiple images and checkboxes. At this point I need to get the values from an input, and then clear it.
To make values empty you can do the following:
$("#element").val('');
To get the selected value you can do:
var value = $("#element").val();
Where #element is the id of the element you wish to select.
You could try:
$('input.class').removeAttr('value');
$('#inputID').removeAttr('value');
A better way is:
$("#element").val(null);
Usual way to empty textbox using jquery is:
$('#txtInput').val('');
If above code is not working than please check that you are able to
get the input element.
console.log($('#txtInput')); // should return element in the console.
If still facing the same problem, please post your code.
Another way is:
$('#element').attr('value', '');
$('.reset').on('click',function(){
$('#upload input, #upload select').each(
function(index){
var input = $(this);
if(input.attr('type')=='text'){
document.getElementById(input.attr('id')).value = null;
}else if(input.attr('type')=='checkbox'){
document.getElementById(input.attr('id')).checked = false;
}else if(input.attr('type')=='radio'){
document.getElementById(input.attr('id')).checked = false;
}else{
document.getElementById(input.attr('id')).value = '';
//alert('Type: ' + input.attr('type') + ' -Name: ' + input.attr('name') + ' -Value: ' + input.val());
}
}
);
});
For me this was the best way to solve this:
$('yourElementName').val(null);