one.('click') reset after click - javascript

I have this jQuery code. I make first lines here as comment, because they are not important in my question, just for structure. I have click event, after click on td I have input field with text in it. I set focus at end of text. But when I have made click, I want to remove focus , so that I can click in middle position of name, and cursor will be there. It works when it is one.('click'), but i need to do it multiple times, so one click works just for one time.
$('td').on('click', function() {
//val = $(this).text();
//console.log(val);
//rowid = $(this).parents('tr').attr('id');
//realclass = $(this).attr('class');
//$("tr").filter("#" + rowid).find("td").filter("." + realclass).find("span").hide(); //hide td->span field..
//$("tr").filter("#" + rowid).find("td").filter("." + realclass).find("input").show();//..and show input field
//get focus on end of input val
SearchInput = $("tr").filter("#" + rowid).find("td").filter("." + realclass).find("input");
strLength = SearchInput.val().length;
SearchInput.focus();
SearchInput[0].setSelectionRange(strLength, strLength);
});

The problem is that clicking on the input itself also triggers the click event on the encompassing <td> element (due to event propagation or "bubbling"), which you don't want to happen. To prevent that you want to call the event.stopPropagation() function when handling click events on the input:
$('td input').on('click', function(e) {
e.stopPropagation();
});

Related

jQuery blur() appears on focus

I want to validate each input of a form on blur() so if user leaves the input box.
$("form#relative_form :input").blur(function() {
var input = $(this).attr('id');
alert("Validate: " + input);
});
It works fine but when i'm in the first input field and hit TAB to get to the next input field,
my script straight validate the second input.
But I want only to validate if i leave the inputs.
JSFiddle
The alert is causing the object to lose focus triggering the blur. Use Console.log() to test instead:
$("form#relative_form :input").blur(function() {
var input = $(this).attr('id'); // This is the jquery object of the input, do what you will
console.log("Validate: " + input);
});
Your code seems to be working fine!!!
But Instead of the alert you must need to use console.log().If you are
using alert then it will continuous call blur function because you are
trying to close the alert box and at that time it will call blur
event.So it's something like circular function.
Instead of:
$("form#relative_form :input").blur(function() {
var input = $(this).attr('id');
alert("Validate: " + input);
});
It should be:
$("form#relative_form :input").blur(function() {
var input = $(this).attr('id');
console.log("Validate: " + input);
});

sap.m.Input change event is triggered when clicking on CheckBox

I have two controls in my page i.e. sap.m.Input and sap.m.CheckBox. There is a change event attached to input field which gives an error bar if input text is not matched with the regex. This change event is triggered on clicking out of focus of the input field. Clicking on checkbox will hide this input and show a third control. Now if i enter something in input field which will not match regex and click on checkbox, It is triggering changeEvent of Input and not even selecting the checkbox. I tried many things like checking in change event whether checkbox is ticked or not, attached a click event on checkbox but no solution.
Please help me so that i will be able to determine the click on checkbox if the current focus is on input field
Here is an example at jsbin. Here error will be thrown if input text contains # and change event is triggered.
var textInput = new sap.m.Text({text:"Area:"})
var inputField =new sap.m.Input("inptId",{
change:function(oEvent){
sap.ui.getCore().byId("barId").setVisible(oEvent.getParameters().value.includes("#"));
}
});
var select = new sap.m.Select("select",
{visible:false,
items:[new sap.ui.core.Item({text:"India"}),
new sap.ui.core.Item({text:"US"}),
new sap.ui.core.Item({text:"UK"})
]
})
var hBox = new sap.m.HBox({items:[textInput,inputField,select]})
var bar = new sap.m.Bar("barId",{
visible:false,
contentMiddle:new sap.m.Text({text:"Error"})
});
var chkBox = new sap.m.CheckBox("chkBxId",{
text:"Select from dropdown",
select:function(oEvent){
var selected = oEvent.getParameters().selected;
sap.ui.getCore().byId("inptId").setVisible(!selected);
sap.ui.getCore().byId("select").setVisible(selected);
sap.ui.getCore().byId("barId").setVisible(false);
}
});
var vBox = new sap.m.VBox({
items:[bar,hBox,chkBox]
});
In this example it is happening sometimes not always but in my project its happening always as there are lot of validations are happening in change event.
#Ashish for focus out try following code.
this.getView().byId("input").addEventDelegate({
onfocusout: function() {
console.log("focus lost !!");
}
}
and for enter key press use following code
.addEventDelegate({
onkeypress: function(e) {
if (e.which === 13) {
do your stuff;
}
}
})
once focus is out it will trigger function provide in onfocusout and while on focus if enter key is pressed it will trigger function provide in onkeypress event.
Also you can merge this in one.
addEventDelegate({
onkeypress: function(e) {
console.log("Enter pressed fouse out", e.which);
},
onfocusout: function() {
do your stuff!
}
})

Drupal gets into loop when calling input text change event

I'm working with Drupal 7, the problem is that I have an input type text for the quantity of the products with 2 arrows in span by default (widget quantity for the add cart button).
When using the js_injector module for getting the 'change()' event of the input, something weird happens and a loop started changing the value of the input for more or less depending of the clicked arrow.
jQuery(function($) {
$(document).ready(function(){
$('#edit-quantity').bind('change keydown keyup click input submit mouseenter', function (e) {alert('Type: ' + e.type); });
});
});
->This works correctly but doesn't get the arrow-span clicked options:
$('#edit-quantity').bind('keydown keyup click input submit mouseenter',...
->These options create a loop:
$('#edit-quantity').bind('change ...',
OR
$('#edit-quantity').change(function (e) {alert('Type: ' + e.type); });
My point is , Why this .change() event creates such a loop? or better how can I stop it to use the event?
Thank you,
You can use "input" instead of change
$('#textbox').on('input', function() {
// do your stuff
});
Better not to use change on text field. Change is more preferred for radio button, select field, check-box etc...
Hope it helps someone, at the end I just did search for all the possibilities of change. Not only in the input also at the 'buttons' represented with span. I did some little trick and ended up like this:
jQuery(function($) {
function value()
{
if($(this).index()!=0) //Just execute once
{
var price=parseFloat(document.getElementsByClassName('field-item')[0].innerHTML.replace(' €','')).toFixed(2);
var quantity = parseFloat($("#edit-quantity").val());
price *= quantity;
var glbvar = price.toFixed(2).replace('.',',')+' €';
//Set Price
document.getElementsByClassName('field-name-commerce-price')[0].getElementsByClassName('field-item')[0].innerHTML = glbvar ;
}
}
$(document).ready(function(){
//When refreshing the value get lost:
if( parseFloat($("#edit-quantity").val()) != 1) value();
/*For input*/ $("#edit-quantity").bind("propertychange keyup paste input",value);
/*For span*/ $('span').bind('click',value);
});
});

Stop element from disappearing when clicked

I'm writing a simple jQuery plugin that will dynamically place a div under a text box whenever it has focus. I've been able to get the position just about right in all the browsers.
I have to attach two event handlers as well on the focus and blur events of the textbox. And it works okay, but the problem is that the div that has been placed under the textbox closes even when we click on it. Now it makes sense why it would so happen, it's because the textbox loses focus, but is there a way I can stop it from happening?
I tried attaching this to the blur event handler -
if($(mainElem).is(":focus")) return;
where mainElem is the div that is shown below the textbox.
Here is a jsFiddle to illustrate the problem.
You are not going to be able to use the blur event if you want to place "clickable" elements in the div that shows. One way to solve this is to bind your event listener to a more global element like the document and then filter out the targets.
Here is a code sample:
$(document).on('click', function (e) {
var targetEl = e.target,
parent = $(e.target).parents()[0];
if (relElem[0] === targetEl || self[0] === targetEl || self[0] === parent) {
$(mainElem).show();
} else {
$(mainElem).hide();
}
});
Here is an update to your fiddle: http://jsfiddle.net/9YHKW/6/
This is a fiddle that I threw together for a project a while back: http://jsfiddle.net/MYcZx/4/
While it is not based off of your fiddle (and I do apologize) I believe that the functionality is much the same as what you're looking for. My example does not include input fields, but rather spans that hold the values. And while I'm not managing focus/blur, you could add a tabIndex attribute to the spans and then add a trigger on focus that would open the menu.
var $sub = $('.subscription');
$sub
.on('click', '.remove', function() {
$(this).parent().remove();
})
.on('click', 'li', function(e) {
var $this = $(this),
$parent = $this.parent(),
$options = $parent.children('li'),
$value = $parent.siblings('.value'),
isMulti = $parent.hasClass('multi'),
values = [];
if(!isMulti) {
$options.removeClass('active');
}
$this.toggleClass('active');
$options.filter('.active').each(function() {
values.push($(this).text());
});
$value.text(values.join(', ') || 'select');
$value[(values.length ? 'add' : 'remove') + 'Class']('set');
});
var $clone = $sub.clone(true);
$('.new')
.on('click', function() {
$(this).before($clone.clone(true));
});

JQuery focus to previous clicked input bug

I have two input fields. The main idea is that whenever you focus to one of the fields, the button click should print a random number inside it.
My problem is that when you just focus on (click on) the first field, then focus on second (or vice versa), the button click prints to both instead of just to the (last) focused field.
You can try to recreate the problem here: http://jsfiddle.net/sQd8t/3/
JS:
$('.family').focus(function(){
var iD = $(this).attr('id');
$("#sets").one('click',function() {
var ra = Math.floor((Math.random()*10)+1);
$('#'+iD).val(ra);
});
});
HTML:
<center class='mid'>
<input type="text" class="family" id="father" />
<br/><br>
<input type="text" class="family" id="mother" />
<br/>
<br/>
<input type='submit' value='Set text' id="sets"/>
</center>
In the "focus" handler, unbind any existing "click" handler:
$('#sets').unbind('click').one('click', function() { ... });
The way you had it, an additional one-shot "click" handler is bound each time a field gets focus, because jQuery lets you bind as many handlers as you like to an event. In other words, calling .one() does not unbind other handlers. When the click actually happens, all handlers are run.
edit — sorry - "unbind" is the old API; now .off() is preferred.
Put the variable iD outside, and separate the functions:
http://jsfiddle.net/sQd8t/8/
This prevents from adding too many events on each input click/focus.
No need to unbind.
var iD;
$('.family').focus(function() {
iD = $(this).attr('id');
});
$("#sets").on('click', function() {
var ra = Math.floor((Math.random() * 10) + 1);
if (iD!="")$('#' + iD).val(ra);
iD = "";
});
See http://jsfiddle.net/sQd8t/11/
$('.family').focus(function(){
$("#sets").attr('data-target',$(this).attr('id'))
});
$("#sets").click(function() {
var target=$(this).attr('data-target');
if(target){
var ra = Math.floor((Math.random()*10)+1);
$('#'+target).val(ra);
}
});
You can create a data-target attribute which contains the field which must be modified.

Categories