Jquery : swap two value and change style - javascript

i need to make a script for select a black div by click(go red), and put black div value into a white div value by another click, this is ok but when i try to swap values of two white case, the change do correctly one time, but if i retry to swap two value of white case the values swap correctly but whitout the background color red.
This is my code :
var lastClicked = '';
var lastClicked2 = '';
$(".blackcase").click(function(e) {
var i = 0;
if ($(this).html().length == 0) {
return false;
} else {
e.preventDefault();
$('.blackcase').removeClass('red');
if (lastClicked != this.id) {
$(this).addClass('red');
var currentId = $(this).attr('id');
var currentVal = $(this).html();
$(".whitecase").click(function(e) {
$('.blackcase').removeClass('red');
var currentId2 = $(this).attr('id');
if (i <= 0 && $("#" + currentId2).html().length == 0) {
$("#" + currentId2).html(currentVal);
$("#" + currentId).html("");
i = 1;
}
});
} else {
lastClicked = this.id;
}
}
});
$(".whitecase").click(function(e) {
var j = 0;
if ($(this).html().length == 0) {
return false;
} else {
e.preventDefault();
$('.whitecase').removeClass('red');
if (lastClicked2 != this.id) {
$(this).addClass('red');
var currentId0 = $(this).attr('id');
var currentVal0 = $(this).html();
$(".whitecase").click(function(e) {
e.preventDefault();
var currentId02 = $(this).attr('id');
var currentVal02 = $(this).html();
if (j <= 0 && currentVal0 != currentVal02) {
$('.whitecase').removeClass('red');
$("#" + currentId02).html(currentVal0);
$("#" + currentId0).html(currentVal02);
j = 1;
return false;
}
});
} else {
lastClicked2 = this.id;
}
}
});
This is JSfiddle :
https://jsfiddle.net/12gwq95u/12/
Try to take 12 and put into first white case, put 39 into second white case, click on the white case with 12 (go red) then click on the white case with 39, the values swap correctly with the red color when it's select, but if you try to reswap two whitecase values thats work but without the red color.
Thanks a lot

I have spent some time to rewrite your code to make it more clear. I don't know what exactly your code should do but according to the information you have already provided, my version of your code is the following:
var selectedCase = {color: "", id: ""};
function removeSelectionWithRed() {
$('div').removeClass('red');
}
function selectWithRed(element) {
removeSelectionWithRed();
element.addClass('red');
}
function updateSelectedCase(color, id) {
selectedCase.color = color;
selectedCase.id = id;
}
function moveValueFromTo(elemFrom, elemTo) {
elemTo.html(elemFrom.html());
setValueToElem("", elemFrom);
}
function setValueToElem(value, elem) {
elem.html(value);
}
function swapValuesFromTo(elemFrom, elemTo) {
var fromValue = elemFrom.html();
var toValue = elemTo.html();
setValueToElem(fromValue, elemTo);
setValueToElem(toValue, elemFrom);
}
function isSelected(color) {
return selectedCase.color == color;
}
function clearSelectedCase() {
selectedCase.color = "";
selectedCase.id = "";
}
function elemIsEmpty(elem) {
return elem.html().length == 0;
}
$(".blackcase").click(function (e) {
if (elemIsEmpty($(this))) {
return;
}
alert("black is selected");
selectWithRed($(this));
updateSelectedCase("black", $(this).attr("id"), $(this).html());
});
$(".whitecase").click(function (e) {
removeSelectionWithRed();
if (isSelected("black")) {
alert("moving black to white");
moveValueFromTo($("#"+selectedCase.id), $(this));
clearSelectedCase();
return;
}
if(isSelected("white") && selectedCase.id !== $(this).attr("id")) {
alert("swap whitecase values");
swapValuesFromTo($("#"+selectedCase.id), $(this));
clearSelectedCase();
return;
}
alert("white is selected");
selectWithRed($(this));
updateSelectedCase("white", $(this).attr("id"), $(this).html());
});
Link to jsfiddle: https://jsfiddle.net/12gwq95u/21/
If my answers were helpful, please up them.

It happens because you have multiple $(".whitecase").click() handlers and they don't override each other but instead they all execute in the order in which they were bound.
I advise you to debug your code in browser console by setting breakpoints in every click() event you have (in browser console you can find your file by navigating to the Sources tab and then (index) file in the first folder in fiddle.jshell.net).
In general I think you should rewrite you code in such a way that you won't have multiple handlers to the same events and you can be absolutely sure what your code does.

Related

Click event works on third or fourth try on button

This is a continuation of This
I used setTimeout() to place cursor on the input fields on pressing the tab, without which the focus goes to a link outside the <div> for some reason I am not aware of.
setTimeout() fixed that issue, but now:
On clicking on submit button the form does nothing but place cursor on the input fields for three or four times then proceeds with submitting.
Here is the submit button functions
$(“#submitbtn”).click(function(e) {
console.log(“click”);
e.preventDefault();
var s = setTimeout(function() {
removeTimeouts();
startValidation();
});
e.stopPropagation();
e.cancelBubble = true;
});
Here is hover function for Submit button
$(“#submitbtn”).mouseover(function(e) {
console.log(“Hover”);
removeTimeouts();
$(“#submitbtn”).focus();
e.preventDefault();
e.stopPropagation();
e.cancelBubble = true;
});
The function removeTimeouts() has all clearTimeout() for all setTimeout() through out the JavaScript file.
But somehow the click function is never works until third or fourth try.
The hover function works on first mouse move though, it prints “Hover” on console, every time the mouse it moves over submit button.
Even after clearing all setTimeout() somehow the focus is moved to input fields instead of proceeding with the console.log() onclick.
Can someone help me understand the issue and help fix the form gets submitted on first click?
Update:
1) This is typed from mobile app, even after re-editing the quote appearing as “” It’s correct in my code just not here.
2) Focus and timeout event is to validate the input fields while moving out of the input field, like if the field is empty, the cursor won’t move to next input field. But just focus is not working, and tab just takes the cursor out of the input fields to a link below it, so time-out helps keeping the cursor the input field.
3) Snippet - This does not replicate the issue as this is by far I can post the code sorry :(
(function ($) {
// Behind the scenes method deals with browser
// idiosyncrasies and such
$.caretTo = function (el, index) {
if (el.createTextRange) {
var range = el.createTextRange();
range.move("character", index);
range.select();
} else if (el.selectionStart != null) {
el.focus();
el.setSelectionRange(index, index);
}
};
// Another behind the scenes that collects the
// current caret position for an element
// TODO: Get working with Opera
$.caretPos = function (el) {
if ("selection" in document) {
var range = el.createTextRange();
try {
range.setEndPoint("EndToStart", document.selection.createRange());
} catch (e) {
// Catch IE failure here, return 0 like
// other browsers
return 0;
}
return range.text.length;
} else if (el.selectionStart != null) {
return el.selectionStart;
}
};
// The following methods are queued under fx for more
// flexibility when combining with $.fn.delay() and
// jQuery effects.
// Set caret to a particular index
$.fn.caret = function (index, offset) {
if (typeof(index) === "undefined") {
return $.caretPos(this.get(0));
}
return this.queue(function (next) {
if (isNaN(index)) {
var i = $(this).val().indexOf(index);
if (offset === true) {
i += index.length;
} else if (typeof(offset) !== "undefined") {
i += offset;
}
$.caretTo(this, i);
} else {
$.caretTo(this, index);
}
next();
});
};
// Set caret to beginning of an element
$.fn.caretToStart = function () {
return this.caret(0);
};
// Set caret to the end of an element
$.fn.caretToEnd = function () {
return this.queue(function (next) {
$.caretTo(this, $(this).val().length);
next();
});
};
}(jQuery));
var allTimeouts = [];
function placeCursor(id) {
id.focus(function(e) {
e.stopPropagation();
//e.cancelBubble();
id.caretToEnd();
});
id.focus();
}
function removeTimeouts(){
for(var i = 0; i < allTimeouts.length; i++) {
clearTimeout(allTimeouts[i]);
}
}
function focusInNumber (id) {
var thisID = id;
var nextID = id + 1;
var preID = id - 1;
//$("#number" + thisID).prop("disabled", false);
var s = setTimeout(function() {
placeCursor($("#number" + thisID));
});
allTimeouts.push(s);
if(preID != 0) {
if($("#number" + preID).val().length <= 0) {
var s = setTimeout(function() {
placeCursor($("#number" + preID));
});
allTimeouts.push(s);
}
}
}
function focusOutNumber (id) {
var thisID = id;
var nextID = id + 1;
var preID = id - 1;
var value = $("#number" + thisID).val();
var regex = new RegExp(/^\d*$/);
var regex1 = new RegExp(/^.*[\+\-\.].*/);
var l = $("#number" + thisID).val().length;
if(!value.match(regex)) {
alert("Just enter numerical digits");
var s = setTimeout(function() {
placeCursor($("#number" + thisID));
},5000);
allTimeouts.push(s);
} else {
if (l<=0) {
alert("This field cannot be empty");
var s = setTimeout(function() {
placeCursor($("#number" + thisID));
},5000);
allTimeouts.push(s);
} else {
if(value.match(regex)) {
var s = setTimeout(function() {
placeCursor($("#number" + nextID));
}, 100);
allTimeouts.push(s);
}
}
}
}
$(document).ready(function(){
$("#number1").focusin(function(){
focusInNumber(1);
});
$("#number1").focusout(function(){
focusOutNumber(1);
});
$("#number2").focusin(function(){
focusInNumber(2);
});
$("#number2").focusout(function(){
focusOutNumber(2);
});
$("#number3").focusin(function(){
focusInNumber(3);
});
$("#number3").focusout(function(){
focusOutNumber(3);
});
$("#number4").focusin(function(){
focusInNumber(4);
});
$("#number4").focusout(function(){
focusOutNumber(4);
});
$("#submitbtn").click(function(e) {
console.log("click");
e.preventDefault();
var s = setTimeout(function() {
removeTimeouts();
alert("startValidation()");
});
e.stopPropagation();
e.cancelBubble = true;
});
$("#submitbtn").mouseover(function(e) {
console.log("Hover");
removeTimeouts();
$("#submitbtn").focus();
e.preventDefault();
e.stopPropagation();
e.cancelBubble = true;
});
});
.SubmitBtn {
width: 100%;
background-color: #cccccc;
}
.Submitbtn:hover {
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" class="reqField" id="number1" placeholder="Enter Number only"></input>
<input type="number" class="reqField" id="number2" placeholder="Enter Number only"></input>
<input type="number" class="reqField" id="number3" placeholder="Enter Number only"></input>
<input type="number" class="reqField" id="number4" placeholder="Enter Number only"></input>
<div id="submitbtn" class="SubmitBtn">Submit</div>
After breaking my head and console.log on all the statement to figure out the flow of code, I was able to find that on $("#submitbtn").click() there is some .focusout() is called.
As these .focusout() were necessary for on the go validation on the <input> fields, i tried to add $.(":focus").blur() and it worked along with adding a return false; on placeCursor() function.
The $.(":focus").blur() removes focus from any currently focused element. And this is a live saver for our logic of code.
So the code looks like
$("#submitbtn").mouseover(function(e) {
console.log("Hover");
$.(":focus").blur();
removeTimeouts();
$("#submitbtn").focus();
e.preventDefault();
e.stopPropagation();
e.cancelBubble = true;
});
....
function placeCursor(id) {
id.focus(function(e) {
e.stopPropagation();
//e.cancelBubble();
id.caretToEnd();
});
id.focus();
return false;
}
Hope this helps someone someday.
Thank you!

After first click of radio button can not fire change event

My jquery change event of radio button not working after first click and does not give any error please help me. i stuck in this from last week.and also cant count proper value because of this problem.
$('input[name="emailing"]').change(function()
{
checkValue();
});
function checkValue(evt) {
alert('hi');
var package = $("#package_value").val();
var emailing = $('input[name="emailing"]:checked').val();
$('input[name="emailing"]').on("mousedown", function() {
var select = $('input[name="emailing"]:checked').val();
$("#selected").val(select);
}).on("mouseup", function() {
$('input[name="emailing"]').prop('checked', false);
$(this).prop('checked', true).checkboxradio("refresh");
});
var selected = $("#selected").val();
alert(selected);
var update = $("#update").val();
if(update != '')
{
var hiddenPackage = $("#hidden_pricing").val();
var hiddenRadion = $("#hidden_radio").val();
var totalValue = package - hiddenRadion;
if(emailing == 1)
{
$("#package_value").val('');
var value = Number(totalValue) + 38;
$("#package_value").val(value);
$("#hidden_package").val(value);
}
if(emailing == 2)
{
$("#package_value").val('');
var value = Number(totalValue) + 55;
$("#package_value").val(value);
$("#hidden_package").val(value);
}
if(emailing == 0)
{
$("#package_value").val('');
var value = Number(totalValue) + 0;
$("#package_value").val(value);
$("#hidden_package").val(value);
}
}
}
You should use delegate
$(document).delegate( "input[name='emailing']", "change", function() {
checkValue();
});
Use on() function with any element id instead of (document)
$(document).on('change', 'input[name="emailing"]', function() {
checkValue();
});

jquery click send function wont work only update the same field

I am trying to make a click send function for my emoticon function but it is not working correctly.
I have created this demo from jsfiddle. In this demo you can se there are four textarea and smiley. When you click smiley then other alert (comments will be come here) changing to (Plese write your comment). What is the problem on there and what is the solution anyone can help me in this regard ?
JS
$('.sendcomment').bind('keydown', function (e) {
if (e.keyCode == 13) {
var ID = $(this).attr("data-msgid");
var comment = $(this).val();
if ($.trim(comment).length == 0) {
$("#commentload" + ID).text("Plese write your comment!");
} else {
$("#commentload" + ID).text(comment);
$("#commentid" + ID).val('').css("height", "35px").focus();
}
}
});
/**/
$(document).ready(function () {
$('body').on("click", '.emo', function () {
var ID = $(this).attr("data-msgid");
var comment = $(this).val();
if ($.trim(comment).length == 0) {
$("#commentload" + ID).text("nothing!");
} else {
$("#commentload" + ID).text(comment);
$("#commentid" + ID).val('').css("height", "35px").focus();
}
});
});
$('body').on('click', '.sm-sticker', function (event) {
event.preventDefault();
var theComment = $(this).parents('.container').find('.sendcomment');
var id = $(this).attr('id');
var sticker = $(this).attr('sticker');
var msg = jQuery.trim(theComment.val());
if (msg == '') {
var sp = '';
} else {
var sp = ' ';
}
theComment.val(jQuery.trim(msg + sp + sticker + sp));
var e = $.Event("keydown");
e.keyCode = 13; // # Some key code value
$('.sendcomment').trigger(e);
});
HTML
At 43 line $('.sendcomment').trigger(e); you trigger keydown event to all textareas. Change it to theComment.trigger(e)

jslint error..Don't make functions within a loop

In the below piece of code I am getting the JSLint error (Don't make functions within a loop). can you help me to modify the code to satisfy the JSLint.
setEllipsis : function () {
$('.co_documentReportTable > thead > tr > th').each(function() {
$(this).find('.co_dcrTable_Header').each(function() {
var $el = $(this);
if($el.css("overflow") === "hidden") {
var text = $el.html();
while ($el.height() > 64) {
$el.text(function (index, text) {
return text.replace(/\W*\s(\S)*$/, '...');
});
//
var txt = 'Fair consideration/no fraudulent conveyance';
if(text.indexOf(txt) !== -1 ) {
$el.text(txt + '...');
}
}
}
});
});
}
I tried creating another function and calling it then in that case while loop is getting executed forever.
Looks in general like you want to use the text-overflow: ellipses CSS property instead here.
Otherwise - pull the anonymous function up and give it a name, so you might end up with :
setEllipsis : function () {
var addEllipses = function(index, text) {
return text.replace(/\W*\s(\S)*$/, '...');
};
$('.co_documentReportTable > thead > tr > th').each(function() {
$(this).find('.co_dcrTable_Header').each(function() {
var $el = $(this);
if($el.css("overflow") === "hidden")
{
var text = $el.html();
while ($el.height() > 64) {
$el.text(addEllipses);
var txt = 'Fair consideration/no fraudulent conveyance';
if(text.indexOf(txt) !== -1 ){
$el.text(txt + '...');
}
}
}
});
});
}

JQuery placeholder HTML5 simulator

I have been using the HTML 5 placeholder and just realised that it does not work outside HTML5 devices. As you can see by the code below the placeholder is always in lowercase and the value is always in upper case.
#maphead input::-webkit-input-placeholder {
text-transform:lowercase;
}
#maphead input:-moz-placeholder {
text-transform:lowercase;
}
<input id="start" type="text" spellcheck="false" placeholder="enter your post code" style="text-transform:uppercase;" class="capital"/>
This is all fine except when dealing with non HTML 5 devices. For this I have employed a bastardised bit of javascript.
function activatePlaceholders() {
var detect = navigator.userAgent.toLowerCase();
if (detect.indexOf("safari") > 0) return false;
var inputs = document.getElementsByTagName("input");
for (var i=0;i<inputs.length;i++) {
if (inputs[i].getAttribute("type") == "text") {
var placeholder = inputs[i].getAttribute("placeholder");
if (placeholder.length > 0 || value == placeholder) {
inputs[i].value = placeholder;
inputs[i].onclick = function() {
if (this.value == this.getAttribute("placeholder")) {
this.value = "";
}
return false;
}
inputs[i].onblur = function() {
if (this.value.length < 1) {
this.value = this.getAttribute("placeholder");
$('.capital').each(function() {
var current = $(this).val();
var place = $(this).attr('placeholder');
if (current == place) {
$(this).css('text-transform','lowercase')
}
});
}
}
}
}
}
}
window.onload = function() {
activatePlaceholders();
}
Firstly this Javascript is rancid. There must be an easier JQuery way. Now although this above does work (reasonably) it does not respond to keeping the placeholder in lowercase and the value in uppercase since it sets the value with the placeholder.
I've set you all up with a nice Fiddle http://jsfiddle.net/Z9YLZ/1/
Try something like this:
$(function() {
$('input[type="text"]').each(function () {
$(this).focus(function () {
if ($(this).attr('value') === $(this).attr('placeholder')) {
$(this).css('text-transform','lowercase');
$(this).attr('value', '');
}
}).blur(function () {
if ($(this).attr('value') === '') {
$(this).css('text-transform','uppercase');
$(this).attr('value', $(this).attr('placeholder'));
}
}).blur();
});
});
Edit: Explicitly declare the text-transform to cascade properly.
Try this one, I'm using it for a while and it works perfectly:
(function($, undefined) {
var input = document.createElement('input');
if ('placeholder' in input) {
$.fn.hinttext = $.hinttext = $.noop;
$.hinttext.defaults = {};
delete input;
return;
}
delete input;
var boundTo = {},
expando = +new Date + Math.random() * 100000 << 1,
prefix = 'ht_',
dataName = 'hinttext';
$.fn.hinttext = function(options) {
if (options == 'refresh') {
return $(this).each(function() {
if ($(this).data(dataName) != null) {
focusout.call(this);
}
});
}
options = $.extend({}, $.hinttext.defaults, options);
if (!(options.inputClass in boundTo)) {
$('.' + options.inputClass)
.live('focusin click', function() {
$($(this).data(dataName)).hide();
})
.live('focusout', focusout);
boundTo[options.inputClass] = true;
}
return $(this).each(function(){
var input = $(this),
placeholder = input.attr('placeholder');
if (placeholder && input.data(dataName) === undefined) {
var input_id = input.attr('id'),
label_id = prefix + expando++;
if (!input_id) {
input.attr('id', input_id = prefix + expando++);
}
$('<label/>')
.hide()
.css('position', options.labelPosition)
.addClass(options.labelClass)
.text(placeholder)
.attr('for', input_id)
.attr('id', label_id)
.insertAfter(input);
input
.data(dataName, '#' + label_id)
.addClass(options.inputClass)
.change(function() {
focusout.call(this);
});
}
focusout.call(this);
});
};
$.hinttext = function(selector, options) {
if (typeof selector != 'string') {
options = selector;
selector = 'input[placeholder],textarea[placeholder]';
}
$(selector).hinttext(options);
return $;
};
$.hinttext.defaults = {
labelClass: 'placeholder',
inputClass: 'placeholder',
labelPosition: 'absolute'
};
function focusout() {
var input = $(this),
pos = input.position();
$(input.data(dataName)).css({
left: pos.left + 'px',
top: pos.top + 'px',
width: input.width() + 'px',
height: input.height() + 'px'
})
.text(input.attr('placeholder'))
[['show', 'hide'][!!input.val().length * 1]]();
}
$($.hinttext);
})(jQuery);
You just need to make sure to style label.placeholder with CSS to look the same as HTML5 placeholder text (color: #999)
Try this: http://jsfiddle.net/msm595/Z9YLZ/12/
Bit late but here's what I do. Store all the default values on page load and then clear value text ONLY when it's the default value that is clicked on. This prevents the JS clearing user entered text.
jQuery(document).ready(function($){
var x = 0; // count for array length
$("input.placeholder").each(function(){
x++; //incrementing array length
});
var _values = new Array(x); //create array to hold default values
x = 0; // reset counter to loop through array
$("input.placeholder").each(function(){ // for each input element
x++;
var default_value = $(this).val(); // get default value.
_values[x] = default_value; // create new array item with default value
});
var current_value; // create global current_value variable
$('input.placeholder').focus(function(){
current_value = $(this).val(); // set current value
var is_default = _values.indexOf(current_value); // is current value is also default value
if(is_default > -1){ //i.e false
$(this).val(''); // clear value
}
});
$('input.placeholder').focusout(function(){
if( $(this).val() == ''){ //if it is empty...
$(this).val(current_value); //re populate with global current value
}
});
});

Categories

Resources