What does this jquery code do? - javascript

$('[role="button"]').click(function () {
myMethod();
});
I know that on click on something it calls myMethod(), but on click on what?
What does role mean?
Is this button?
<input type="button" ... />
What is: [role="button"] ?

It is an attribute equals selector. $('[role="button"]') would select all elements that has attribute role set to button.
For ex:
All below three will be selected when you do $('[role="button"]')
<div role="button" ></div>
<p role="button" ></p>
<button role="button"></button>
But this will not
<input type="button">

Selector with attribute role whose value is button
$('[role="button"]') ; // It is not the button in context
//
<input role="button" ... /> // this is selected
<input type="button" ... /> // Not this
<input role="button" ... /> // this is selected

The selector is selecting on the role attribute that is equal to button.

It's the attribute equals selector
http://api.jquery.com/attribute-equals-selector/

Related

remove readonly from input

I have a pice of code that copy 2 3 divs and the div contains a readonly property.
After that I have a button that says to edit when I click on that button this should remove the readonly and the input field is available to edit.
My code that doesn't work!
my javascript code:
I have tried removeAttr, prop('readonly', false), attr('readonly', false)
$("body").on("click", ".btn",function(){
if($(this).is("#edit")){
$(this).parents(".control-group").removeAttr('readonly');
}else if($(this).is("#save")){
}else if($(this).is("#remove")){
$(this).parents(".control-group").remove();
}
});
The div that I copy:
<div class="control-group input-group" style="margin-top:10px">
<input id="rule" type="text" class="form-control" readonly>
<div class="input-group-btn">
<button id="edit" class="btn btn-danger remove" type="button"><i class="glyphicon glyphicon-remove"></i> Edit</button><button id="remove" class="btn btn-danger remove" type="button"><i class="glyphicon glyphicon-remove"></i> Remove</button>
</div>
</div>
I hope that when i click on edit the readonly disappear and after a click on save and the readonly back again.
Thanks for the help
PS: the remove button works!
You may have better luck with .attr as readonly is an attribute and not a property. See this (Specifically, attributes vs properties)
One issue I see with your code is this line here:
$(this).parents(".control-group").removeAttr('readonly');
You are trying to remove the readonly attribute from a div. I think you mean to remove it from your .form-control which is an input
Maybe try $(this).parents(".control-group").find('input.form-control').removeAttr('readonly'); (i'd do some null checks here. Plenty can go wrong if the selector fails)
Here's a basic example of how to toggle the readonly attribute using jQuery
var readonly = true;
$('button').on('click', (e) => {
readonly = !readonly
$('input').attr('readonly', readonly);
// Extra
if (readonly) {
$('input').attr('placeholder', "I'm readonly");
} else {
$('input').attr('placeholder', "I'm not readonly");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input readonly placeholder="I'm readonly" />
<button>Toggle Readonly</button>
You're applying remove to the wrong element.
Try this:
$("body").on("click", ".btn",function(){
if($(this).is("#edit")){
$(this).parents(".control-group").find('input').removeAttr('readonly');
}
...
}
});
Using the find jQuery function, you can call every input element inside the .control-group element. To further expand the functionality, say, to include select elements or other buttons (with a unlock-readonly class, for instance), you can try:
$(this).parents(".control-group").find('input, select, .unlock-readonly').removeAttr('readonly');

Way to know which button was clicked - Angular 5

I'm developing a quiz app have 4 options for a given question. I have already written a func to verify if the clicked option is correct answer or wrong.I'm having problem in knowing which option was selected by user and I want to style it using CSS as - If the wrong option is selected, the clicked option would turn red and the correct option would turn green in color and vice versa.
HTML :
<div *ngFor="let actiVar of activeArray ;let j = index" >
{{actiVar.QuestionID}}.{{actiVar.Question}}
<br>
<br>
<button type="button" name="s" id="one" (click)="filterAnswer(actiVar.OP[j+0]) ; getColor(actiVar.OP[j+0])" [ngStyle]="{backgroundColor: buttonColor}" [disabled]="permissionoptions">{{actiVar.OP[j+0]}}</button>
<br>
<br>
<button type="button" name="s" id="two" (click)="filterAnswer(actiVar.OP[j+1]) ; getColor(actiVar.OP[j+1])" [ngStyle]="{backgroundColor: buttonColor}" [disabled]="permissionoptions">{{actiVar.OP[j+1]}}</button> <br>
<br>
<button type="button" name="s" id="three" (click)="filterAnswer(actiVar.OP[j+2]) ; getColor(actiVar.OP[j+2])" [ngStyle]="{backgroundColor: buttonColor}" [disabled]="permissionoptions">{{actiVar.OP[j+2]}}</button> <br>
<br>
<button type="button" name="s" id="four" (click)="filterAnswer(actiVar.OP[j+3]) ; getColor(actiVar.OP[j+3])" [ngStyle]="{backgroundColor: buttonColor}" [disabled]="permissionoptions">{{actiVar.OP[j+3]}}</button>
<br>
</div>
I have set a getColor func onclick of the option selected but what it does is,if a wrong option is selected by the user,it turns all the 4 options to red and vice versa.It doesn't specifically turn the clicked option to red.
getColor(j: any) {
if (j == this.activeArray[0].isRight) {
this.buttonColor = 'green';
}
else {
this.buttonColor = 'red';
}
}
this.activeArray[0].isRight is the correct answer retrieved from JSON.
I understand that I will have to make use of individual id tag on button to know which option-button was clicked but I had no luck finding the correct logic on stackoverflow.
You can use a Template reference variables -> https://angular.io/guide/template-syntax#ref-vars
<button #buttonRef1 type="button" (click)="filterAnswer(actiVar.OP[j+0], buttonRef1)" [disabled]="permissionoptions">{{actiVar.OP[j+0]}}</button>
<button #buttonRef2 type="button" (click)="filterAnswer(actiVar.OP[j+1], buttonRef2)" [disabled]="permissionoptions">{{actiVar.OP[j+1]}}</button>
<button #buttonRef3 type="button" (click)="filterAnswer(actiVar.OP[j+2], buttonRef3)" [disabled]="permissionoptions">{{actiVar.OP[j+2]}}</button>
<button #buttonRef4 type="button" (click)="filterAnswer(actiVar.OP[j+3], buttonRef4)" [disabled]="permissionoptions">{{actiVar.OP[j+3]}}</button>
filterAnswer:
filterAnswer(answer: string, button: HTMLButtonElement) {
// Do logic here
button.style.backgroundColor = desiredColor; // example: "#f00"
}
You can use the own filterAnswer method for passing the name of the button. This aprroach its the easier way to make it.
<button type="button" name="s" id="one" (click)="filterAnswer(actiVar.OP[j+0], 'one') ; getColor(actiVar.OP[j+0])" [ngStyle]="{backgroundColor: buttonColor}" [disabled]="permissionoptions">{{actiVar.OP[j+0]}}</button>
You have to pass $event as another argument and get id from that object
check this solution
Angular2 get clicked element id

jQuery: trigger click or focus input field

I have a page with multiple divs that all look like the example below.
Each div contains a field, a hidden field and a button.
How can I achieve that by click on the button the (visible) input field gets triggered ?
I need to trigger either a click or focus as both fire the same function.
Each button in question has the class="triggerBtn" and the corresponding input field has the class="inputField".
Example div:
<div>
<input type="text" class="inputField" id="field1" name="field1" />
<input type="hidden" name="field1" />
<button type="button" class="btn btn-primary triggerBtn">Find</button>
</div>
I guess you want:
$(".triggerBtn").click(function () {
$(this).closest('div').find('.inputField').focus();
});
add
Onclick="function()" see here
if you need to trigger it manually using jquery you can to this by
$("#field1").trigger("click");
see also here
$(".triggerBtn").on("click",function(e){
$(this).closest("div").find(".inputField").click();
//or $(this).closest("div").find(".inputField").focus();
});
$(".triggerBtn").parent().children("input[type:text]").first().focus()
Updated Jsfiddle: http://jsfiddle.net/ZmL4y/3/
$(document).on("click",".triggerBtn", function() {
var inputField = $(this).closest('div').find('.inputField');
if($(inputField).is(":visible"))
{
$(inputField ).focus();
}
});

How can I make it necessary for the user to click a button for the form to be validated?

I have a group of buttons, and ONE of them needs to be clicked in order to proceed to the next form:
<div class="btn-group" data-toggle="buttons-radio">
<button type="button" class="btn" data-bind="click: sportYes">Yes</button>
<button type="button" class="btn" data-bind="click: sportBasic">Basic</button>
<button type="button" class="btn" data-bind="click: sportNo">No</button>
</div>
I am using jquery validate, and I want to write a validate method but I can't use my typical approach, such as giving a text field a value of required, e.g.
$("#FormThatNeedsToBeValidated").validate({
rules: {
textinput1: {
required: true
},
textinput2: {
required: true
}}});
Even if I knew the syntax, I don't think this would help, since not ALL buttons are required.
Is there a way to leverage the active attribute that's rendered when one of my three buttons is clicked?
A <button> is not eligible for validation using this plugin.
This plugin will only work on the following eight kinds of data input elements (each must have a unique name attribute), which also must be contained within a form element:
<form>
<!-- Textbox Input - Also including the various HTML5 input types -->
<input type="text" name="something" />
<!-- Password Input -->
<input type="password" name="pw" />
<!-- Radio Button -->
<input type="radio" name="foo" />
<!-- Checkbox -->
<input type="checkbox" name="bar" />
<!-- File Upload -->
<input type="file" name="upload" />
<!-- Hidden Input - 'ignore: []' must be defined in the options -->
<input type="hidden" name="hide" />
<!-- Select Dropdown -->
<select name="foobar"> ... </select>
<!-- Text Area Box -->
<textarea name="barfoo"></textarea>
</form>
Also see the "reference" page in the docs: http://jqueryvalidation.org/reference/
To achieve the desired effect, you can test & submit the form upon clicking a particular button. Use the .valid() method to test/check and submit() to submit the form.
HTML:
<button type="button" class="btn" id="sportYes">Yes</button>
<button type="button" class="btn" id="sportBasic">Basic</button>
<button type="button" class="btn" id="sportNo">No</button>
jQuery:
$(document).ready(function() {
$("#FormThatNeedsToBeValidated").validate({ // <- initialize plugin on form
// rules & options
});
$('#sportYes').on('click', function() {
// stuff to do when this button is clicked
if ($("#FormThatNeedsToBeValidated").valid()) { // <- test validity
// stuff to do on valid form
$("#FormThatNeedsToBeValidated").submit(); // <- submit the valid form
}
});
$('#sportBasic').on('click', function() {
// stuff to do when this button is clicked
});
$('#sportNo').on('click', function() {
// stuff to do when this button is clicked
});
});
DEMO: http://jsfiddle.net/PgCr2/

Jquery closest does not work?

I'm trying to build a general function that get's called from four different checkboxes. When the checkbox is checked it should remove the attribute disabled from a button near the checkbox.
my buttons all have diffrent classes like this
button 1: class="button primary pie list-buy-button list_buy_button_1903"
button 2: class="button primary pie list-buy-button list_buy_button_1901"
button 3: class="button primary pie list-buy-button list_buy_button_1899"
button 4: class="button primary pie list-buy-button list_buy_button_1897"
first i bind the event to my checkboxes
$(".avtalsbox").each(function()
{
$(this).click(function()
{
chbclickeventhandler(this);
});
});
then i handle it with this function.. this i where i encounter a problem
i have tried many solutions but noone works?
function chbclickeventhandler(thebox)
{
if (thebox.checked) {
//SOLUTION 1
var button = $(thebox).closest("[class*='buy_button']");
$(button).removeAttr("disabled");
//SOLUTION 2
var button = $(thebox).parent().children("[class*='buy_button']");
$(button ).removeAttr("disabled");
}
}
this is how my html looks like
<div class="buyonly boxhighlight varmepaket1">
<div width="100%" style="float:right;">
<!---köpknapp--->
<form class="product_form" action="/shoppingcart/increase_product_count/" method="post">
<input type="hidden" name="quantity" value="1" id="quantity">
<span class="button-container pie">
<!-- THIS IS THE INPUT I WANT TO REMOVE DISABLED FROM ASWELL AS ADD IT -->
<input class="button primary pie list-buy-button list_buy_button_1903" type="submit" value="Beställ idag!" disabled="">
</span>
<!---crap--->
<input type="hidden" name="product_id" value="1903">
<input type="hidden" name="article_number" value="varmepaket2">
</form>
<!---köpknapp END--->
</div>
<div width="" style="float:right;">
<a href="#" onclick="eb_klarna_sum=14990; $('body').find('#klarna_payment').click(); return false;">
<img class="symbol" src="/layouts/focus/klarna_symbol.png"> Dela upp betalningen från xxx kr/mån</a></div>
<div style="float:left;"><input type="checkbox" class="avtalsbox" name="godkannavtalet" value="varmepaket1">Jag godkänner avtalet!</div>
</div>
Your usage of closest is incorrect try this way: Closest will only get you to the parent or itself provided there is a match in the selector. So here use closest to get to the parent div with the class .buyonly and find for the button inside that.
$(".avtalsbox").change(chbclickeventhandler);
function chbclickeventhandler() {
if (this.checked) {
//SOLUTION 1
var button = $(this).closest(".buyonly").find("[class*='buy_button']");
$(button).prop("disabled", false);
}
}
Fiddle
If you are looking to toggle the button then you can just do:
$(".avtalsbox").change(chbclickeventhandler);
function chbclickeventhandler() {
$(this)
.closest(".buyonly")
.find("[class*='buy_button']")
.prop("disabled", !this.checked);
}
In your case checkbox is not a children of button, so you cannot use closest!
use
$(thebox).closest('.product_form').find(["class*='buy_button']");

Categories

Resources