Space keypress on an HTML Label interpreted as checkbox click - html

When I add 'click' event handler on an HTML checkbox with a label, then space keypress on the label causes the checkbox's click event handler to be executed. I would like to prevent that. (The checkbox itself is hidden / not visible - this is done in some version of Bootstrap framework used in my code).
HTML:
<body>
<label for="checkbox" id="label">Click on me, I am Label for <strong>hidden</strong> Checkbox</label>
<!-- checkbox is not visible -->
<input type="checkbox" id="checkbox" style="opacity: 0" />
<!-- to be filled by JavaScript code -->
<div id="checkboxValue"></div>
</body>
JavaScript code:
import { fromEvent } from 'rxjs';
const checkbox: HTMLInputElement = document.querySelector('#checkbox');
const checkboxValue: HTMLDivElement = document.querySelector('#checkboxValue');
function updateCheckbox() {
checkboxValue.innerHTML = `Checkbox ${
checkbox.checked ? '✔️ (checked)' : '❌ (unchecked)'
}`;
}
// event handler for the checkbox being executed also for Space keypress:
fromEvent(checkbox, 'click').subscribe((event) => {
console.log('checkbox CLICK -------')
updateCheckbox();
});
updateCheckbox();
Open the Stackblitz console, click the Click on me, I am Label for hidden Checkbox.
Then press the space key and see the click handler being executed.
Demo on Stackblitz.

If a label has keyboard focus, pressing the Space key also raises the Click event.
If you want to remove focus, you can add a blur event (on the label) to remove focus so spacebar won't function to click the button :
e.target.blur();

Related

.val() returns empry strings when i try to fetch value of input in modal [duplicate]

I have a form in Angular that has two buttons tags in it. One button submits the form on ng-click. The other button is purely for navigation using ng-click. However, when this second button is clicked, AngularJS is causing a page refresh which triggers a 404. I’ve dropped a breakpoint in the function and it is triggering my function. If I do any of the following, it stops:
If I remove the ng-click, the button doesn’t cause a page refresh.
If I comment out the code in the function, it doesn’t cause a page refresh.
If I change the button tag to an anchor tag (<a>) with href="", then it doesn’t cause a refresh.
The latter seems like the simplest workaround, but why is AngularJS even running any code after my function that causes the page to reload? Seems like a bug.
Here is the form:
<form class="form-horizontal" name="myProfile" ng-switch-when="profile">
<fieldset>
<div class="control-group">
<label class="control-label" for="passwordButton">Password</label>
<div class="controls">
<button id="passwordButton" class="secondaryButton" ng-click="showChangePassword()">Change</button>
</div>
</div>
<div class="buttonBar">
<button id="saveProfileButton" class="primaryButton" ng-click="saveUser()">Save</button>
</div>
</fieldset>
</form>
Here is the controller method:
$scope.showChangePassword = function() {
$scope.selectedLink = "changePassword";
};
If you have a look at the W3C specification, it would seem like the obvious thing to try is to mark your button elements with type='button' when you don't want them to submit.
The thing to note in particular is where it says
A button element with no type attribute specified represents the same thing as a button element with its type attribute set to "submit"
You can try to prevent default handler:
html:
<button ng-click="saveUser($event)">
js:
$scope.saveUser = function (event) {
event.preventDefault();
// your code
}
You should declare the attribute ng-submit={expression} in your <form> tag.
From the ngSubmit docs
http://docs.angularjs.org/api/ng.directive:ngSubmit
Enables binding angular expressions to onsubmit events.
Additionally it prevents the default action (which for form means sending the request to the server and reloading the current page).
I use directive to prevent default behaviour:
module.directive('preventDefault', function() {
return function(scope, element, attrs) {
angular.element(element).bind('click', function(event) {
event.preventDefault();
event.stopPropagation();
});
}
});
And then, in html:
<button class="secondaryButton" prevent-default>Secondary action</button>
This directive can also be used with <a> and all other tags
You can keep <button type="submit">, but must remove the attribute action="" of <form>.
I wonder why nobody proposed the possibly simplest solution:
don't use a <form>
A <whatever ng-form> does IMHO a better job and without an HTML form, there's nothing to be submitted by the browser itself. Which is exactly the right behavior when using angular.
Add action to your form.
<form action="#">
This answer may not be directly related to the question. It's just for the case when you submit the form using scripts.
According to ng-submit code
var handleFormSubmission = function(event) {
scope.$apply(function() {
controller.$commitViewValue();
controller.$setSubmitted();
});
event.preventDefault();
};
formElement[0].addEventListener('submit', handleFormSubmission);
It adds submit event listener on the form.
But submit event handler wouldn't be called when submit is initiated by calling form.submit(). In this case, ng-submit will not prevent the default action, you have to call preventDefault yourself in ng-submit handler;
To provide a reasonably definitive answer, the HTML Form Submission Algorithm item 5 states that a form only dispatches a submit event if it was not submitted by calling the submit method (which means it only dispatches a submit event if submitted by a button or other implicit method, e.g. pressing enter while focus is on an input type text element).
See Form submitted using submit() from a link cannot be caught by onsubmit handler
I also had the same problem, but gladelly I fixed this by changing the type like from type="submit" to type="button" and it worked.
First Button submits the form and second does not
<body>
<form ng-app="myApp" ng-controller="myCtrl" ng-submit="Sub()">
<div>
S:<input type="text" ng-model="v"><br>
<br>
<button>Submit</button>
//Dont Submit
<button type='button' ng-click="Dont()">Dont Submit</button>
</div>
</form>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.Sub=function()
{
alert('Inside Submit');
}
$scope.Dont=function()
{
$scope.v=0;
}
});
</script>
</body>
Just add the FormsModule in the imports array of app.module.ts file,
and add import { FormsModule } from '#angular/forms'; at the top of this file...this will work.

Changing edited textbox value to the original passed value on clicking outside the div of textbox in reactJS

Please refer the image attached first by clicking on here.
There is a textbox which retrieves the original value from the state. Now, if any user changes textbox's value and click's outside the div then the textbox value must be replaced with the original value obtained from the state i.e 2000 here. If the user clicks on edit after changing the value in the textbox then that value must be updated in the state.
Any suggestions to perform this task.
Code sample is appreciated.
Thank you in advance.
I had the same issue. I found the solution that outside div onClick event you set state to original value and input div add onclick event stopPropagation so click on this div outside onClick event not called and edit button add onclick or onSubmit(if you use form) event for perform edit login.
Sample code is here.
this.state = {
flag: false,
number: 0,
oldNumber: 0
}
handleEditMaxAmount =()=>{
// edit code here.
}
outClickHandle =()=>{
if(this.state.flag){
this.setState({
number: oldNumber
})
this.state.flag = false
}
}
inClickHandle =()=>{
this.state.flag = true;
}
<div onClick={this.outClickHandle}>
...
<div onClick={(e)=>{e.stopPropagation();}}>
<input type="number" value={this.state.number} onChange={this.inClickHandle} name="number" />
<button onClick={this.handleEditNumber}>Edit </button>
</div>
...
</div>

Prevent expand on click on prime ng accordion

I have an primeng accordion and the accordion header has a checkbox control . Whenever i check/uncheck checkbox , the accordion tab is getting open/closed automatically
Is there any way to prevent expand/collapse on click on checkbox ? It should expand/collapse on header other than check/uncheck check box ?
This is happening due to Event Bubbling. For this need to stop eventPropagation by calling stopPropagation() of MouseEvent.
Accordion html code sample
<p-accordion>
<p-accordionTab header="Godfather I" [selected]="true">
<p-header>
<span>Godfather I
<input type="checkbox" (click)="onClick($event)">
</span>
</p-header>
Some Text
</p-accordionTab>
</p-accordion>
Corresponding component ts code.
onClick($event: MouseEvent){
$event.stopPropagation();
}
For Reference added stackblitz code sample.
This is how I solved this issue. This is happening because of Event Bubbling. So when you click on child element. Event propagate to its parent and so on. So Just use stop propagation on event. It will prevent the click event on your accordion. Below code for your reference.
Accordian with Check box code I used (onChange) method.
<p-accordionTab>
<p-header>
<div class="ui-g" style="width:250px;margin-bottom:10px">
<div class="ui-g-12"><p-checkbox name="group1" #ck value="New York" label="New York" [(ngModel)]="selectedCities" (onChange)="checkChange($event)" inputId="ny"></p-checkbox></div>
</div>
</p-header>
</p-accordionTab>
component.ts
selectedCities: string[] = [];
//Simply you have to to stop propogation here.
checkChange(e:any){
console.log(e); // true or false.
event.stopPropagation(); // component will have direct access to event here.
}

How to call a function on click in x-editable form (Twitter Bootstrap)

I have a input text field inside a div(x-editable form). I need to call a Jquery function on the button click. How to do so.?
This is my div
<div class="input-append"><input type="text" id="WorkloadName" placeholder="enter your workload name" name=""></div>
This is my jquery function for x-editable form
jQuery.noConflict();
(function($) {
$(function() {
jQuery.fn.editable.defaults.mode = 'inline';
jQuery('#WLElementName').editable();
});
})(jQuery);
In x-editable form after clicking the textfield a form will appear, i need to call the function on the click of the submit button (blue button with tick mark, I could not post the image here since I don't have enough reputation score)
I tried calling the function using the class name of the button but its not coming. please help me to fix this
In your .editable declaration, add a dictionary parameter
url: function(params) {}
and perform your task in there.
See http://vitalets.github.com/x-editable/docs.html#editable for further documentation.

How to keep focus on text field at all times (MVC 4 c#)

I have a text field that always needs to be focused no matter what the user does.
I have activated the text field on load by doing this:
<html>
<head>
< script type ="text/javascript" src ="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></ script>
< script type ="text/javascript">
$( function () {
$( "#myTextBox2" ).focus();
});
</ script>
</head>
< body>
< div>
< input type ="text" id ="myTextBox">
< input type ="text" id ="myTextBox2"onblur="var that= this; setTimeout(function() { that.focus(); }, 0);">
</ div>
</ body>
</html>
If I press the tab button when trying the code above I can still tab away from myTextBox2, but I cant click on myTextBox with my mouse (which is right).
If the user presses any button or clicks anywhere on the site the text field should still be selected and focused. How do I enforce this completely?
Edit:
Adding this to the header in my code and to the answer by Sven seems to do the trick:
$(document).keydown(function(objEvent) {
if (objEvent.keyCode == 9) { //tab pressed
objEvent.preventDefault(); // stops its action
}
})
Credit:
Lock tab key with javascript?
You can keep the focus on the text field at all time with the following code:
HTML:
<form>
<input type="text" name="name" id="focus" />
<input type="text" name="name2" />
<input type="text" name="name3" />
<input type="text" name="name4" />
</form>
JS:
$(document).ready(function() {
$("#focus").focus().bind('blur', function() {
$(this).focus();
});
$("html").click(function() {
$("#focus").val($("#focus").val()).focus();
});
//disable the tab key
$(document).keydown(function(objEvent) {
if (objEvent.keyCode == 9) { //tab pressed
objEvent.preventDefault(); // stops its action
}
})
});​
Example on JsFiddle: Click!
I had to replace the value of the textfield to force/trigger the placement of the cursor in the focused field.
Hope this helps.
I would to the following:
1) On page load, make the element focused automatically ( already done by you )
2) On #myTextBox2 create a key press event handler and discard every char except of the "real" input ones e.g. alfanumeric, dots, carets, and everything the user can actually input on that field
3) Create an onblur event handler on #myTextBox2 that actually focuses on the same input ( already done by you, I would suggest to put it on a script in the )
4) For completeness, put an Interval on your page that checks every X microseconds that the input is focused. If not, make the input focused. This is optional.
Be aware that, in any case, if a function call actually detects that the input is not focused, and has to focus it, the focus will be pointed at the beginning of the input, so the user input will re-begin from the beginning of the input field. The input contents will not be destroyed, however the user will have to jump to the end of the input after the re-focus.
If you need any help in creating the event handlers, just ask.