How to get the value of a <td> with jQuery? - javascript

What I want to do is when I double click on a cell a textbox appears to update the cell data. Then I want to get the value updated. For now I tried this :
$('#previsionnel td').dblclick(function () {
var $this = $(this);
var input = $('<input>', {
value: $this.text(),
type: 'text',
blur: function () {
$this.text(this.value);
},
keyup: function (e) {
if (e.which === 13)
input.blur();
}
}).appendTo($this.empty()).focus();
var test = $this.find("input").val();
console.log(test);
$('#previsionnel td').change(function () {
console.log(test);
});
});
Everything works, except I just can't get the data updated with $(this).text() In my console log the result is empty.
Some screenshots of what is supposed to do :
As you can see in the last screenshot, the second value in the console must be 5000 and not 100000.00.

First you need to use $(this).val() in the function below:
blur: function() {
$(this).val(this.text);
},
Second, Because your input is a child of td then use .find("input") as in:
var test = $(this).find("input").val();
I've also moved your .change() function out of your .dblclick(). Reason is that the above "test" variable will only be set when you double click the td, not when you change it.
$('#previsionnel td').dblclick(function() {
var input = $('<input>', {
value: $(this).text(),
type: 'text',
blur: function() {
$(this).val(this.text);
},
keyup: function(e) {
if (e.which === 13)
input.blur();
}
}).appendTo($(this).empty()).focus();
var test = $(this).find("input").val();
console.log(test);
$('#previsionnel td').change(function() {
test = $(this).find("input").val();
console.log(test);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="previsionnel">
<tr>
<td>something</td>
</tr>
</table>

1) There is syntax error - unclosed handler dblclick
$('#previsionnel td').dblclick(function () {
var input = $('<input>', {
value: $(this).text(),
type: 'text',
blur: function () {
$(this).text(this.value);
},
keyup: function (e) {
if (e.which === 13)
input.blur();
}
}).appendTo($(this).empty()).focus();
var test = $(this).text();
console.log(test);
$('#previsionnel td').change(function () {
console.log(test);
});
});
2) If you use AJAX logic for getting data in the table, try to use event handler on();. Because
'Delegated events have the advantage that they can process events from
descendant elements that are added to the document at a later time.'
E.g.
$('body').on('dblclick', '#previsionnel td', function () {
var input = $('<input>', {
value: $(this).text(),
type: 'text',
blur: function () {
$(this).text(this.value);
},
keyup: function (e) {
if (e.which === 13)
input.blur();
}
}).appendTo($(this).empty()).focus();
var test = $(this).text();
console.log(test);
$('#previsionnel td').change(function () {
console.log(test);
});
});

In this line $(this).val(this.text); this refers to the text box. I am guessing you want to update the td? Try the below snippet
$('#previsionnel td').on( "dblclick", function() {
var input = $('<input>', {
value: $(this).text(),
type: 'text',
blur: function() {
$(this).parent("td").text($(this).val());
$(this).hide();
},
keyup: function(e) {
if (e.which === 13)
input.blur();
}
}).appendTo($(this).empty()).focus();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="previsionnel">
<tr>
<td>something</td>
<td>something2</td>
</tr>
</table>

var input; // Please declare input as globaly declare
$('#previsionnel td').dblclick(function () {
var test;
input = $('<input>', {
value: $(this).text(),
type: 'text',
blur: function () {
test = $(this).text(this.value);
},
keyup: function (e) {
if (e.which === 13)
input.blur();
}
}).appendTo($(this).empty()).focus();
var test = $(input).val();//use input variable instead this
console.log(test);
});
$(document).on('blur','input',function () {
console.log($(this).val()); //get value outside event listener
});

Related

Need to simulate keypress jquery

I have a function that uses the value of a textbox (prodinput) to hide/show links in a dropdown list. It works when a user types in a string manually but when I want to auto-populate the value by passing a url parameter I'll need to trigger a keyup or keydown to get it to call the function.
Here is the function that does the search (located in the core.js):
prodinput.on('keyup, keydown',function() {
var search = $(this).val().toLowerCase();
$('.support-product .browse-products a').each(function() {
if($(this).text().toLowerCase().search(search) > -1) {
$(this).parent().show();
} else {
$(this).parent().hide();
}
});
});
Here is the function I'm using to trigger the function above (located on the page I'm trying to run it on.
$(function(){
$target = $('.browse-products .display');
$target.val($trimmed);
$('.browse-products').addClass('active');
$target.focus();
var e = jQuery.Event( "keydown" );
$target.trigger(e);
});
I've tried using:
$target.keyup();
and as shown above:
var e = jQuery.Event( "keydown" );
$target.trigger(e);
I'm wondering if it's a problem with the order in which things load on the page.
I'd put your keyup code in a named function.
$(function () {
myFunction();
prodinput.on('keyup, keydown', function () {
myFunction();
})
};
var myFunction = function () {
var search = $('#prodinput').val().toLowerCase();
$('.support-product .browse-products a').each(function () {
if ($(this).text().toLowerCase().search(search) > -1) {
$(this).parent().show();
} else {
$(this).parent().hide();
}
});
};
Assuming you don't need to support ancient browsers you can just listen for the input event which covers keypress and change events. Then after attaching the listener simply trigger the event:
$(function() {
$("#prodinput").on('input', function() {//alternatively you could use change and keyup
var search = $(this).val().toLowerCase();
$('.support-product .browse-products a').each(function() {
if ($(this).text().toLowerCase().search(search) > -1) {
$(this).parent().show();
} else {
$(this).parent().hide();
}
});
}).trigger("input");//trigger the event now
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="search" id="prodinput" value="peanuts" />
<div class="support-product">
<ul class="browse-products">
<li>jam</li>
<li>elephants</li>
<li>peanuts</li>
</ul>
</div>

How to get value inside .html() in JQuery

I am trying to implement an inline edit of Todo lists. I have this code and I want to be able to get the value inside it.
$(function clickedit() {
$(".a").dblclick(function (e) {
e.stopPropagation();
var currentEle = $(this);
var value = $(this).html();
var id_val = $(this).attr('value');
//alert(id_val);
updateVal(currentEle, value, id_val);/**/
});
});
function updateVal(currentEle, value, id_val) {
$(currentEle).html('<input class="thVal" id="aaa" type="text" value="' + value + '" />'); // i want to get the value inside the input
var aaa = $('#aaa').val();
$(".thVal").focus();
$(".thVal").keyup(function (event) {
if (event.keyCode == 13) {
alert(aaa);
$.post('includes/edit-task3.php', { task_name: aaa, task_id: id_val}, function() {
$(currentEle).html($(".thVal").val().trim());
alert('in');
//current_element.parent().fadeOut("fast", function() { $(this).remove(); });
});
}
});
$(document).click(function () {
$(currentEle).html($(".thVal").val().trim());
});
}
How can I get the current value in the input inside .html()?
I tried, var aaa = $('#aaa').val(); but it does not work.. How can I do this?
Thank you so much for your help.
Don't put your events in a function that is triggered by something else
$(".thVal").keyup(function (event) {
if (event.keyCode == 13) {
var aaa = $(this).val();
alert(aaa);
$.post('includes/edit-task3.php', { task_name: aaa, task_id: id_val}, function() {
$(currentEle).html($(".thVal").val().trim());
alert('in');
//current_element.parent().fadeOut("fast", function() { $(this).remove(); });
});
}
});
Use .find(SELECTOR)
$(currentEle).find('#aaa').val();
Edit: As updateVal function could be invoked many times, you will have multiple ID having same value in the DOM. Make sure the ID must be unique

Edit HTML text on click

I would like to change text to input text by clicking on it :
Currently I've:
<div class="wrapper">
<span class="text-content">Double Click On Me!</span>
</div>
And in javascript:
//plugin to make any element text editable
$.fn.extend({
editable: function () {
$(this).each(function () {
var $el = $(this),
$edittextbox = $('<input type="text"></input>').css('min-width', $el.width()),
submitChanges = function () {
if ($edittextbox.val() !== '') {
$el.html($edittextbox.val());
$el.show();
$el.trigger('editsubmit', [$el.html()]);
$(document).unbind('click', submitChanges);
$edittextbox.detach();
}
},
tempVal;
$edittextbox.click(function (event) {
event.stopPropagation();
});
$el.dblclick(function (e) {
tempVal = $el.html();
$edittextbox.val(tempVal).insertBefore(this)
.bind('keypress', function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
submitChanges();
}
}).select();
$el.hide();
$(document).click(submitChanges);
});
});
return this;
}
});
//implement plugin
$('.text-content').editable().on('editsubmit', function (event, val) {
console.log('text changed to ' + val);
});
But I don't know how to change double click on simple click ! I've tried to replace $el.dblclick(...) by $el.click(), but it doesn't work.
Is anybody have a solution ?
When you just change $el.dblclick to $el.click it will also handled with $(document).click(submitChanges); event. So $el.click handler should return false to stop further event processing.
$el.click(function (e) { // <---------- click
tempVal = $el.html();
$edittextbox.val(tempVal).insertBefore(this).bind('keypress', function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
submitChanges();
}
}).select();
$el.hide();
$(document).click(submitChanges);
return false; // <------------------------ stop further event handling
});
http://jsfiddle.net/zvm8a7cr/
You may use the contenteditable attribute of html
var initialContent = $('.text-content').html();
$('.text-content')
.on('blur', function(){
if(initialContent != $(this).html())
alert($(this).text());
if($(this).html() == ''){
$(this).html(initialContent);
}
})
.on('click', function(){
if(initialContent == $(this).html()) {
$(this).html('');
}
});;
.text-content {
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="wrapper">
<span contenteditable="true" class="text-content">Click On Me!</span>
</div>

show div when all input fields have content

I have a form with a few input fields, I only want to show a div when all the input fields got content, when one of the input fields has no content the div should disappear again.
I made it work with one input field, but how do I get it to work when all the input fields are filled in (don't know if its a good clean way?):
$(function () {
$('input').change(function() {
$('.next').toggle($(this).val().length !== 0);
}); });
Fiddle:
http://jsfiddle.net/uQyH9/19/
Try this : http://jsfiddle.net/uQyH9/21/
$(function () {
var _cached=$('input');
_cached.change(function() {
if (_cached.filter(function (){return $(this).val().length }).length==_cached.length)
$('.next').show();
else
$('.next').hide();
});
});
You can use a filter function to check that all the input are filled.
Code:
$(function () {
$('input').change(function () {
$('.next').toggle($("input").filter(function () {
return this.value === "";
}).length === 0)
});
});
Demo: http://jsfiddle.net/IrvinDominin/DwF2P/
UPDATE
You can check the value of the elements by type by cheking type attribute.
Code:
$(function () {
$('input').change(function () {
$('.next').toggle($("input").filter(function () {
var myType=$(this).attr("type");
if (myType === "checkbox") return !$(this).is(":checked");
if (myType==="radio"){
var myName = $(this).attr("name");
if (myName==="") return !$(this).is(":checked");
return $('input[name='+ myName +']:checked').length===0
}
return this.value === "";
}).length === 0)
});
});
Demo: http://jsfiddle.net/IrvinDominin/pqJhg/
Loop over the inputs. If you find one that isn't filled in, then hide the DIV. If you don't, show the DIV.
$('input').change(function() {
var allFilled = true;
$('input').each(function() {
if (this.value === '') {
allFilled = false;
return false; // Terminate the loop
}
}
$('.next').toggle(allFilled);
});

Key event for ajax call does not work

I am making an application where, when the user presses Enter, it should make an ajax call.
I used a plugin to browse the items and created jQuery code for the "click" (worked perfectly).
The problem is that when I make it so that pressing Enter calls the ajax code, there is some kind of conflict and it does not work.
Does anyone have any solution or another method?
thanks.
javascript
var main = function () {
var url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%3D'http%3A%2F%2Frss.cnn.com%2Fservices%2Fpodcasting%2Fac360%2Frss.xml'%20AND%20itemPath%3D%22%2F%2Fchannel%22&format=json&diagnostics=true&callback=?";
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function (json) {
// titulos
var titles = json.query.results.channel.item.map(function (item) {
return item.title;
});
// urls
var urls = json.query.results.channel.item.map(function (item) {
return item.origLink;
});
$(".container-list-podcast ul").append('<li>' + titles.join('</li><li>'));
$(".container-list-podcast ul li").each(function (key, value) {
var text = $(this).text();
$(this).html('<a class="link-podcast" href="' + urls[key] + '">' + text + '</a>');
});
// Load KeyNavigation
a = $('.nav_holder li a').keynav(function () {
return window.keyNavigationDisabled;
});
},
error: function (e) {
console.log(e.message);
}
});
}(jQuery);
///
$(document).ready(function () {
// Call Ajax Click <-- work
$('.container-list-podcast').on('click', '.link-podcast', function (e) {
e.preventDefault();
$('.video').attr('src', this.href);
});
// Call Ajax Key Enter <-- dont work
$('.container-list-podcast').on('keypress', '.selected', function (e) {
e.preventDefault();
if (e.which == 13) { // keyCode 13 == Enter key
$('.video').attr('src', this.href);
}
});
});
jsfiddle
$('body').on('keydown', function (e) {
e.preventDefault();
if (e.which == 13) { // keyCode 13 == Enter key
$('.selected').trigger('click', function() {
$('.video').attr('src', this.href);
});
}
});
You can try binding a keydown event to body or document it will full fill your purpose.
Actually the keypress event will not be triggered by an a element unless it has a focus. It would be more garantee to bind this event to the document.
Change your function to that:
// Call Ajax Key Enter
$(document).on('keypress', function (e) {
if (e.which == 13) { // keyCode 13 == Enter key
$('.video').attr('src', $('.container-list-podcast .selected').prop('href'));
}
e.preventDefault();
});
JSFiddle Example

Categories

Resources