hello dear programmers,
i'm trying to update table fields with ajax.
doubleclick on a table cell, the cell content will be replaced with a textbox and after changing the text, it updates the cell value with the textbox value.
my problem is, the first change works fine, but after the second change, all table cells changed before are updated with the new value and not only the one clicked.
would be great if someone can help me out and point me to right direction.
you can find the whole thing to test on http://jsfiddle.net/bDxDX/3/
$(function () {
$(".doodleEdit").dblclick(function (e) {
e.stopPropagation();
var currentEle = $(this);
var value = $(this).html();
updateVal(currentEle, value);
});
});
function updateVal(currentEle, value) {
$(currentEle).html('<input class="thVal" type="text" value="' + value + '" />');
var mode = $(currentEle).attr('class').split(' ')[1];
if (mode == 'editDescr') {
alert("editDescr");
} else if (mode == 'addDate') {
alert("addDate");
} else if (mode == 'addVote') {
alert("addVote");
}
$(".thVal").focus();
$(".thVal").keyup(function (event) {
if (event.keyCode == 13) {
$(currentEle).html($(".thVal").val().trim());
}
});
$(document).click(function () {
$(currentEle).html($(".thVal").val().trim());
});
}
http://jsfiddle.net/bDxDX/3/
many thanks and best regards
costal
Does this solve your case ? Please check this jsfiddle -
http://jsfiddle.net/hellomaya/bDxDX/5/
$(function () {
$(".doodleEdit").dblclick(function (e) {
e.stopPropagation();
var currentEle = $(e.target);
var value = $(e.target).html();
console.log($(e.target));
if ($.trim(value) === "") {
$(currentEle).data('mode', 'add');
} else {
$(currentEle).data('mode', 'edit');
}
updateVal(currentEle, value);
});
});
function updateVal(currentEle, value) {
$(currentEle).html('<input class="thVal" type="text" value="' + value + '" />');
var mode = $(currentEle).data('mode');
alert(mode);
$(".thVal").focus();
$(".thVal").keyup(function (event) {
if (event.keyCode == 13) {
$(this).parent().html($(this).val().trim());
$(".thVal").remove();
}
});
}
$(document).click(function (e) {
if ($(".thVal") !== undefined) {
if ($(".thVal").val() !== undefined) {
$(".thVal").parent().html($(".thVal").val().trim());
$(".thVal").remove();
}
}
});
I just did something very similar and thought this was a pretty concise way to do it. It assumes you want use the Enter key (key code 13) to write the input data back to the table cell, and Escape (code 27) to close the input without writing to the cell.
$("#table").on('dblclick', 'td', function() {
var cell_data = $(this).text();
$(this).replaceWith('<td><input id="temp_enter"></input></td>');
$("#temp_enter").keyup( function(event) {
if (event.which == 13) {
$(this).parent().replaceWith('<td>' + $(this).val() + '</td>');
} else if (event.which == 27) {
$(this).parent().replaceWith('<td>' + cell_data + '</td>');
}
});
});
Related
This question already has answers here:
Check if a value already exists on a <li> tag with jQuery
(4 answers)
Closed 5 years ago.
Edit: solved by this code
$("input[type='text']").keypress(function(event) {
if (event.which === 13) {
var todoText = " " + $(this).val();
var lis = $("li");
if ($(lis).filter(function() {
return $(this).text() == todoText;
}).length === 0) {
$('ul').append("<li> " + $.trim($(this).val()) + "</li>");
$(this).val('').attr("placeholder", "Add New Todo").val("").removeClass('alert');
return false;
} else {
$(this).attr("placeholder", "Todo exist").val("").addClass('alert');
return false;
}
}
});
The filter function helps me to solve the problem. TXz a lot
Check the solution below. It is always better to manage the state somewhere rather than directly updating/checking the DOM.
$(document).ready(function() {
var todoItems = ["Go to home", "Buy cavolo", "Fried chicken"];
function renderItems() {
var items = todoItems.map(function(item) {
return '<li>' + item + '</li>'
});
$("#items").html(items.join(''));
}
renderItems();
$("input[type='text']").keypress(function(event) {
if (event.which === 13) {
if ($(this).val()) {
if (todoItems.indexOf($(this).val()) == -1) {
todoItems.unshift($(this).val());
renderItems();
$(this).val('')
} else {
alert("todo exist!");
}
}
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="Add New Item" />
<ul id="items">
</ul>
Try below code:
$(document).ready(function(){
$("input[type='text']").keypress(function(event) {
if (event.which === 13 && $.trim($(this).val()) !== '') {
if ($('ul li:contains('+$.trim($(this).val())+')').length ) {
alert('todo exist!');
return false;
} else {
$('ul').append('<li>'+$.trim($(this).val()) +'</li>');
$(this).val('')
}
}
});
});
I can't figure this out. It's probably something small which I can't process at the moment. I am a beginner in this, sorry.
Now I am working on this chat, every time I press enter a class is being created with username and message.
On the left side of username, I want to put this img profile which the user can chose, or just use the default.png.
I want the picture to remain on the left side of his name before deleting.
Here is some of the code:
<script>
$("#message").keypress(function(e) {
var test = $("#Uname").val()
var valmsg = $('#message').val();
var poza = $('<img src="http://dev.alurosu.com/bobo/chat/data/img/admin/default.png">');
if(e.which == 13 && valmsg.trim() == "" ){
e.preventDefault();
alert('Please type a message to send');
} else if (e.which == 13) {
$("#chat").append("<div class='mesaj' >" + test + ':' + valmsg + "</div>");
$("#chat").append(poza);
$('#message').val('');
e.preventDefault();
}
});
</script>
And here is Jsfiddle but I couldn't upload the complete code.
And here is a screenshot exemple
Hope you can explain to me somehow. Thank You.
else if (e.which == 13) {
var imgpath = '<img src="https://cdn4.iconfinder.com/data/icons/small-n-flat/24/user-group-512.png" width="30px" height="30px" style="float:right">';
$("#chat").append("<div class='mesaj' >" + test + ':' + valmsg + imgpath +"</div>");
$('#message').val('');
}
use this code ..
I assume you want the image to be followed by the Username,so you should be using Prepend.
$('div.mesaj').prepend(yourimage);
Do make sure the image path is correct.
$(document).ready(function () {
$("#Uname").click(function () {
$("#popUp").show();
});
$(".pophide").click(function () {
$("#popUp").hide();
});
// display previous stored username, if set
var prevUname = localStorage.getItem("user");
if (prevUname !== null) {
$("#Uname").val(localStorage.getItem("user"));
}
$("#save").click(function () {
var valoare = $("#userSet").val();
if (typeof (Storage) !== "undefined") {
// Store
localStorage.setItem("user", valoare);
// Retrieve
$("#Uname").val(localStorage.getItem("user"));
} else {
$("#Uname").val("Sorry, your browser does not support Web Storage...");
}
});
$("#message").keypress(function (e) {
var test = $("#Uname").val();
var image = "<img src='https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcSlk3gZnCZExtx8vMg5ykXThHnVmk4SjFZpwYysmCiuBXxQFXQhmg' />";
var valmsg = $('#message').val();
if (e.which == 13 && valmsg.trim() == "") {
e.preventDefault();
alert('Please type a message to send');
} else if (e.which == 13) {
$("#chat").append("<div class='mesaj' >" + test + ':' + valmsg + image + "</div>");
$('#message').val('');
}
});
$("#chat").on("click", ".mesaj", function () {
console.log("Merge click clasa");
$("#yes").click(function () {
$(".mesaj").remove();
$("#delPop").hide();
});
$("#delPop").show();
$("#no").on("click", function () {
$("#delPop").hide();
});
});
});
Add CSS
#chat img {
float: right;
height: 30px;
}
I have a requirement of having a text-box with default value say "PF_". If I type something and press control+backspace All the values are been deleted. This problem occurs only If I have an underscore "_" at the end.
Javascript
var readOnlyLength = $('#field').val().length;
$('#output').text(readOnlyLength);
$('#field').on('keypress, keydown', function (event) {
var $field = $(this);
$('#output').text(event.which + '-' + this.selectionStart);
if ((event.which != 37 && (event.which != 39)) && ((this.selectionStart < readOnlyLength) || ((this.selectionStart == readOnlyLength) && (event.which == 8)))) {
return false;
}
});
Html
<input id="field" type="text" value="PF_" size="50" />
I have tried a sample fiddle.
Any Idea?
I'm not sure if this is what you're after, but this will reset the field to the previous value if the user tries to modify the read-only part:
$('#field').on('keypress, keydown', function (event) {
var $field = $(this);
var old = $field.val();
setTimeout(function(){
if($field.val().slice(0,3)!='PF_') {
$field.val(old);
}
},0);
});
Edit: in response to op's comments, try this code instead:
$('#field').on('keypress, keydown', function (event) {
var $field = $(this);
if(event.ctrlKey && event.which==8) { // ctrl-backspace
$field.val('PF_');
return false;
}
var old = $field.val();
setTimeout(function(){
if($field.val().slice(0,3)!='PF_') {
$field.val(old);
}
},0);
});
Fiddle
This is how I would do it:
$("#field").keyup(function(e){
if($(this).val().length < 3){
$(this).val("PF_");
}
});
Here is the JSFiddle demo
How can I prevent my form from submitting until all required fields are populated? Required fields could be input, select, etc.
Below is my current code which is not working. Basically after I click on the submit button I would like to iterate through each field in the form which has tag='required' and if all fields are populated/selected then allow form submit.
Thanks.
$("#submitButton").click(function (e) {
var submit = false;
var count = 0;
$('#Form input, #Form select').each(function () {
var id = $(this).attr('id');
var value = $('#' + id).val();
var tagValue = $('#' + id).attr('tag');
var isDisabled = $('#' + id).is(':disabled');
if (isDisabled == false) {
if ($('#' + id).is(':visible')) {
if (tagValue == 'required') {
if (id == 'email') {
validateEmail('#' + id);
}
if (id == 'phone') {
validatePhone('#' + id);
}
if ($('#' + id).hasClass("currency")) {
validateCurrency('#' + id);
}
if ($('#' + id).is('select')) {
if (value == '' || value == 'Unknown' || value == 'unassigned' || value == null) {
$('#' + id).css({
'border': '1px solid #F70D1A'
});
}
}
else if (value == "") {
$('#' + id).css({
'border': '1px solid #F70D1A'
});
}
if (value == '' || value == 'Unknown' || value == 'unassigned' || value == null) {
submit = false;
} else {
submit = true;
}
}
}
}
});
if (!submit) {
e.preventDefault();
}
});
Rather than attaching this event to the button click, you should attach it to the form on submit:
$('#Form').on('submit', function (e) {
//-- your current code should work fine, put it here
});
I went ahead and cleaned up your method:
$("#Form").on('submit', function (e) {
var submit = true;
//-- use find+filter to reduce the set of matched elements
$(this).find('input, select').filter('[tag="required"]:visible:enabled').each(function () {
var $this = $(this),
value = $this.val();
//-- switch for unique flags
switch ($this.attr('id')) {
case 'email': validateEmail($this); break;
case 'phone': validatePhone($this); break;
}
//-- continue parsing non-unique flags
if ($this.hasClass('currency')) validateCurrency($this);
if (!value || value === 'Unknown' || value === 'unassigned') {
$this.css('border', '1px solid #F70D1A');
submit = false;
}
});
if (!submit) {
e.preventDefault();
}
});
Things to note:
I removed all of the unnecessary ID-based lookups. This is a huge performance hit, and should be reduced to a single $(this) lookup which you should reuse.
I am currently passing $this to each validate method, so they will have to be updated accordingly.
Rather than iterating through all select/input fields, I reduced the matched elements first, cutting down on unnecessary code.
I simplified your logic to the best of my understanding based on the code provided.
I switched the method used on the submit flag. It now starts out as valid and will be set to false if any item fails the check.
$('#Form').on('submit', function (e) {
$.each(this.find("[tag='required']"),function(i,item)
{
validation logic goes here.
....
}
)});
I want to change keycode in keydown ( key press ) in all input in a page.I want to replace Enter keycode with TAB key code. How I can do this?
thanks
EDIT 1)
Consider this code:
<div>
<asp:RadioButtonList ID="RadioButtonList1" runat="server">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
<asp:ListItem>4</asp:ListItem>
</asp:RadioButtonList>
<br />
<br />
<asp:TextBox ID="TextBox1" runat="server">3333</asp:TextBox>
<br />
<br />
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
</asp:DropDownList>
</div>
I want when user press Enter on eny of above control focus go to next control.
thanks
I've had a similar problem, where I wanted to press + on the numpad to tab to the next field. Now I've released a library that I think will help you.
PlusAsTab: A jQuery plugin to use the numpad plus key as a tab key equivalent.
Since you want enter/↵ instead, you can set the options. Find out which key you want to use with the jQuery event.which demo.
JoelPurra.PlusAsTab.setOptions({
// Use enter instead of plus
// Number 13 found through demo at
// https://api.jquery.com/event.which/
key: 13
});
Then enable the feature by adding plus-as-tab="true" to the form fields you want to use enter-as-tab in, or some other element that contains these form fields. Radio buttons should not be a problem, as they are covered by my other library, EmulateTab - see autonavigation of radio buttons in that demo.
<div plus-as-tab="true">
<!-- all focusable elements inside the <div> will be enabled -->
<asp:RadioButtonList ID="RadioButtonList1" runat="server">
<!-- Radio buttons should not be a problem. -->
</asp:RadioButtonList>
</div>
You can try it out yourself in the PlusAsTab enter as tab demo.
This code is to replace enter with tab character:
$("#wmd-input").bind("keypress", function(e) {
if (e.keyCode == 13) {
var input = $(this);
var inputVal = input.val();
setTimeout(function() {
input.val(inputVal.substring(0,inputVal.length) + "\t");
}, 1);
}
});
Live Demo
UPDATE:
This code is to focus to on the next element:
$(document).ready(function () {
$("input,select").bind("keydown", function (e) {
if (e.keyCode == 13) {
var allInputs = $("input,select");
for (var i = 0; i < allInputs.length; i++) {
if (allInputs[i] == this) {
while ((allInputs[i]).name == (allInputs[i + 1]).name) {
i++;
}
if ((i + 1) < allInputs.length) $(allInputs[i + 1]).focus();
}
}
}
});
});
Hope this works
$('input,textarea').keydown(function(){
if(event.keyCode==13) {
event.keyCode = 9;
}
});
Edit
Try this http://jsfiddle.net/GUmUg/. Play around with selectors to make this work as i don't know asp
$('input,textarea').keypress(function(e){
if(e.keyCode==13) {
$(this).next().focus();
}
});
$('input').on('keydown',function(e){
var keyCode = e.keyCode || e.which;
if(e.keyCode === 13) {
e.preventDefault();
$('input')[$('input').index(this)+1].focus();
}
});
check fiddle here : http://jsfiddle.net/Pd5QC/
The way I do it is by using jquery to each over your selection and focusing on the element after the current on you are on.
$(document).on('keyup', '.my-input', function (ev) {
if (ev.keyCode == '13') {
var currentInput = this;
var isOnCurrent = false;
$('.my-input').each(function () {
if (isOnCurrent == true) {
$(this).focus();
return false;
}
if (this == currentInput) {
isOnCurrent = true;
}
});
}
});
I think this work:
$('input').live("keypress", function (e) {
/* ENTER PRESSED*/
var OffSet = 0;
if (e.keyCode == 13) {
/* FOCUS ELEMENT */
if ($(this).is("input[type='radio']")) {
var tblID = $(this).closest('table').attr('id');
var radios = $('#' + tblID).find(":input");
//alert(radios.index(this));
OffSet = radios.length - radios.index(this) - 1;
}
//alert(OffSet);
var inputs = $(this).parents("form").eq(0).find(":input");
var idx = inputs.index(this);
inputs[idx + OffSet].blur();
try {
inputs[idx + OffSet].selectionStart = inputs[idx + OffSet].selectionEnd = -1;
} catch (e) {
}
if (idx == inputs.length - 1) {
inputs[0].select();
} else {
inputs[idx + 1 + OffSet].focus(); // handles submit buttons
try {
inputs[idx + 1 + OffSet].select();
} catch (e) {
}
}
return false;
}
});
I created a simple jQuery plugin which does solve this problem. It uses the ':tabbable' selector of jQuery UI to find the next 'tabbable' element and selects it.
Example usage:
// Simulate tab key when enter is pressed
$('.myElement').bind('keypress', function(event){
if(event.which === 13){
if(event.shiftKey){
$.tabPrev();
}
else{
$.tabNext();
}
return false;
}
});
$(document).ready(function() {
//Objetos con CssClass="EntTab" sustituye el Enter (keycode 13) por un Tabulador (keycode 9)!!
$(".EntTab").bind("keypress", function(e) {
if (e.keyCode == 13) {
var inps = $("input, select"); //add select too
for (var x = 0; x < inps.length; x++) {
if (inps[x] == this) {
while ((inps[x]).name == (inps[x + 1]).name) {
x++;
}
if ((x + 1) < inps.length) $(inps[x + 1]).focus();
}
} e.preventDefault();
}
});
});