Way to know which button was clicked - Angular 5 - javascript

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

Related

Button combination

I want to get input from the user in a type="number" text box.
the limitation is a number between 1994-1998.
I currently have two buttons. One "submit" button and a second ("button") button that goes to the next screen.
I want to make the 2 buttons one.
Which means that as soon as I click the "Move to Next page" button, the input is also checked.
And you can move to the next screen only with proper input.
would much rather do it only with HTML and less with JavaScript if possible.
If there is no option then it is also possible with JavaScript.
function check () {
console.log('Checked!');
}
<div>
between 1994 and 1998: <input id="section5input" type="number" name="quantity" min="1994" max="1998">
<input type="submit">
Calculate the answers!
</div>
</div>
<div class="box" id="section6">
<h1>fin!</h1>
<div class="question-text">
<input style="padding: 20px;" type="button" class="btn" onclick="check();">check!!!
</div>
</div>
From what I understand you want to go to next page only if input is correct then check this out. I have created a form and placed your html inside it. Now the submit button will only work if check function return true.
function check(){
//return true, if correct
//return false, if incorrect
return true;
}
<form action='yourURLforNextPage' method="POST">
Between 1994 and 1998:
<input id="section5input" type="number" name="quantity" min="1994" max="1998">
<input type="submit" onclick="return check();">
</form>
function check(){
let val = document.getElementById("section5input");
if((val.value!= "" && null) && (val.value> 1994 && val.value<1998) ){
//code to render to next screen
}
}

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']");

What does this jquery code do?

$('[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/

Show/hide forms using buttons and JavaScript

I need to show a form using a button, and hide it when the user presses another button, because the other button shows another form. I did a similar thing with a select box, but I can't figure out how to do this.
Use the following code fragment to hide the form on button click.
document.getElementById("your form id").style.display="none";
And the following code to display it:
document.getElementById("your form id").style.display="block";
Or you can use the same function for both purposes:
function asd(a)
{
if(a==1)
document.getElementById("asd").style.display="none";
else
document.getElementById("asd").style.display="block";
}
And the HTML:
<form id="asd">form </form>
<button onclick="asd(1)">Hide</button>
<button onclick="asd(2)">Show</button>
There's something I bet you already heard about this! It's called jQuery.
$("#button1").click(function() {
$("#form1").show();
};
It's really easy and you can use CSS-like selectors and you can add animations. It's really easy to learn.
If you have a container and two sub containers, you can do like this
jQuery
$("#previousbutton").click(function() {
$("#form_sub_container1").show();
$("#form_sub_container2").hide(); })
$("#nextbutton").click(function() {
$("#form_container").find(":hidden").show().next();
$("#form_sub_container1").hide();
})
HTML
<div id="form_container">
<div id="form_sub_container1" style="display: block;">
</div>
<div id="form_sub_container2" style="display: none;">
</div>
</div>
There's the global attribute called hidden. But I'm green to all this and maybe there was a reason it wasn't mentioned yet?
var someCondition = true;
if (someCondition == true){
document.getElementById('hidden div').hidden = false;
}
<div id="hidden div" hidden>
stuff hidden by default
</div>
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/hidden
Would you want the same form with different parts, showing each part accordingly with a button?
Here an example with three steps, that is, three form parts, but it is expandable to any number of form parts. The HTML characters « and » just print respectively « and » which might be interesting for the previous and next button characters.
shows_form_part(1)
/* this function shows form part [n] and hides the remaining form parts */
function shows_form_part(n){
var i = 1, p = document.getElementById("form_part"+1);
while (p !== null){
if (i === n){
p.style.display = "";
}
else{
p.style.display = "none";
}
i++;
p = document.getElementById("form_part"+i);
}
}
/* this is called at the last step using info filled during the previous steps*/
function calc_sum() {
var sum =
parseInt(document.getElementById("num1").value) +
parseInt(document.getElementById("num2").value) +
parseInt(document.getElementById("num3").value);
alert("The sum is: " + sum);
}
<div id="form_part1">
Part 1<br>
<input type="number" value="1" id="num1"><br>
<button type="button" onclick="shows_form_part(2)">»</button>
</div>
<div id="form_part2">
Part 2<br>
<input type="number" value="2" id="num2"><br>
<button type="button" onclick="shows_form_part(1)">«</button>
<button type="button" onclick="shows_form_part(3)">»</button>
</div>
<div id="form_part3">
Part 3<br>
<input type="number" value="3" id="num3"><br>
<button type="button" onclick="shows_form_part(2)">«</button>
<button type="button" onclick="calc_sum()">Sum</button>
</div>

javascript + div tags

these days i read and learn more about my problem!the code is here:
<div align="right" id="parent" name="parent">
<select name="select30" id="select30" value=""/>here inside i have options values and work dynamically with query to my DB</select>
<input type="button" id="moreFields" value="+" onclick=""/> //add select tags
<input type="button" value="-" onclick="" /> //remove select tags
<div name="child" id="writeclone"></div> //here cloned the child from parent DIV
</div>
<input type="button" name="enter" id="" value="ENTER" onclick="getoptionvalues();"/>
My problem is how i can get the names or id's from child DIV when + button fired.When this button fired create child DIVs in Child DIV!!Can anybody HELP ME to correct my JAVASCRIPT code
<script>
function getoptionvalues() {
var parent=document.getElementById('parent');
for (var count=0;count<parent.childNodes.length;count++) {
if(parent.childNodes[count].tagName =='DIV') {
alert ('parent.childNodes[count]');
}
}
}
</script>
As ThiefMaster pointed out, 'parent.childNodes[count]' should be parent.childNodes[count]. Then to get the id, it is just .id and name is .name
if(parent.childNodes[count].tagName =='DIV') {
alert (parent.childNodes[count].id);
alert (parent.childNodes[count].name);
}
At the very least, you need to add a method name to your onClick:
<input type="button" id="moreFields" value="+" onclick="$:getoptionvalues()"/>
Then, using jquery, you can grab an array of components of a certain type, and then loop through w/ alerts:
function getoptionvalues() {
var dropdownMenus = $("select");
dropdownMens.each(function () {
var id = $(this).id;
alert(id);
});
}

Categories

Resources