compare data from article to button - javascript

I am trying to create a "quiz" page where a user can guess if an article is real or fake. I have data-info from my database that I am trying to compare with the data-info for a button clicked by the user to check if they are correct or not. For example, if the data-info of the article is true, and the user clicks the button with data-info true then alert " you're right" or whatever. Someone please help!!
function loadArticle(){
$.get("/api/article", function(response){
$(".header").html(response[0].Headline);
$("h1").attr("data-info", response[0].is_real);
$(".body" ).html('<a target="_blank" href="${response[0].web_address}"> ${response[0].web_address} </a>');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class = "row" id="answers">
<button data-info="false" type = "button" class = "fa-bounce fas fa-times col-xs-4 col-xs-offset-2" id="fake">
FAKE
</button>
<div class="col-xs-4"></div>
<button data-info="true" type = "button" class = "fa-bounce fas fa-check col-xs-4 col-xs-offset-2" id="real">
REAL
</button>
</div>

You can compare data-* with the jQuery method .data()
here is an example when you get the data from the api request and compare its value when you click on the "real" button for example:
<button id="real" data-info="true">
real
</button>
<button id="real" data-info="false">
fake
</button>
var dataToCompare;
function loadArticle(){
$.get("/api/article", function(response){
dataToCompare = response[0].is_real;
}
}
$('#real').click(function() {
var data = $(this).data('info');
if(data === dataToCompare) {
alert('yes');
}
})

Related

Javascript not un-clicking button with link

Newish to javascript, but I do't know why the below is not working. I am trying to use javascript to make a link become active after a button has become clicked.
The user clicks a button that updates the HTML, changes the class and adds a html link. The code works the first time -- the HTML is updated correctly. However if the user decides to un-click the button nothing happens.
Javascript:
function agree() {
let agreement = document.getElementById("agreement");
let agree = document.getElementById("agree");
agree.onclick = () => {
if (agree.value === true) {
agreement.innerHTML = `
<button id="agree" class="agree--no" value="false"></button>I agree
<div class="btn--no-schedule">
<a href="#" > No SCHEDULE </a>
</div> `
} else {
agreement.innerHTML = `
<button id="agree" class="agree--checked" value="true"><i class="fas fa-lg fa-check-square"></i></button>I agree
<div class="btn--agree-schedule">
<a href="http://google.com" > yes SCHEDULE </a>
</div> `
}
}
};
HTML
<div id="agreement">
<button id="agree" class="agree--no" value="false"></button>I agree
<div class="btn--no-schedule">
<a href="#" > SCHEDULE </a>
</div>
</div>
I also tried
<button onclick=“agree();” id="agree" class="agree--no" value="false"></button>
but get a type error agree() is not a function.
Any help would be appreciated
There are two errors here.
First, the click event is lost when you reset the agreement's innerHTML, second, agree.value is a string, and thus will never be "=== true".
There are multiple ways of fixing it. One way is changing the innerHTML part so the event isn't lost. Also, changing the condition to === 'true'
Like so:
HTML:
<div id="agreement">
<button id="agree" class="agree--no" value="false"></button>I agree
<div id="schedule-btn" class="btn--no-schedule">
<a href="#" > SCHEDULE </a>
</div>
</div>
JS:
function agree() {
const agreeBtn = document.getElementById("agree");
const scheduleBtn = document.getElementById("schedule-btn");
agreeBtn.onclick = () => {
if (agreeBtn.value === "true") {
agreeBtn.value = false;
scheduleBtn.innerHTML = `
<div class="btn--no-schedule">
<a href="#" > No SCHEDULE </a>
</div>
`;
} else {
agreeBtn.value = true;
scheduleBtn.innerHTML = `
<div class="btn--agree-schedule">
<a href="http://google.com" > yes SCHEDULE </a>
</div>
`;
}
};
}
Edit: I tried to alter your code as little as possible
Try this code:
function ChangeContent(checkbox) {
var el = document.getElementsByClassName("schedule-agreement")[0];
(checkbox.checked) ? el.innerText = "No SCHEDULE": el.innerText = "Yes SCHEDULE"
}
<div id="agreement">
<input type="checkbox" onchange="ChangeContent(this)"> I agree
<div>
SCHEDULE
</div>
</div>
Explanation:
First of all, add a change event listener to the input checkbox. Then, whenever it is run, check if it is checked. If it is, change the link's innerText to "No SCHEDULE", otherwise, change it to "Yes SCHEDULE".
If you need to use a button, then I would recommend adding a click event listener (or an onclick inline event listener), and changing the link innerText ONLY - not the whole HTML.
In that case, here's a separate demo:
var isChecked = false
function ChangeContent() {
isChecked = !(isChecked)
if (isChecked) {
document.getElementsByClassName("agree")[0].innerText = "✔️ I agree"
document.getElementsByClassName("schedule-agreement")[0].innerText = "No SCHEDULE"
} else {
document.getElementsByClassName("agree")[0].innerText = "❌ I agree"
document.getElementsByClassName("schedule-agreement")[0].innerText = "Yes SCHEDULE"
}
}
<div id="agreement">
<button class="agree" onclick="ChangeContent()">I agree</button>
<div class="btn--no-schedule">
SCHEDULE
</div>
</div>

Change the outcome of a variable based on a button push to match a different button

I have a button with an id that sets a global variable like this:
<div class="mybuttons"
<button id="mapOne" data-toggle="modal" data-target="#map-1-scene-1">Scene</button>
<button class="no-click-span" id="mapOneCurrent" data-toggle="modal" data-target="#map-1-scene-1"><i class="fas fa-charging-station fa2x"></i> Current</button>
</div>
Then in JS:
var mapNumber;
const mybuttons = document.querySelectorAll('.mybuttons button');
mybuttons.forEach(mybutton => {
mybutton.addEventListener('click', processClick);
});
function processClick() {
window.mapNumber = this.id; // the id of the clicked button
}
The second button in the div with the id #mapOneCurrent just reopens the modal without refreshing the data.
What I would like to happen, is if the second button is pushed (eg #mapOneCurrent) that the variable mapNumber just remains as mapOne (without the word "Current" at the end of it). So it would almost be as if the other button had been pushed.
Is this possible to do in this type of scenario?
This should do what you want:
var mapNumber;
const mybuttons = [...document.querySelectorAll('.mybuttons button')];
mybuttons.forEach(mybutton=>{
mybutton.addEventListener('click',function() {
window.mapNumber = this.id.replace("Current",""); // the id of the clicked button
console.log(mapNumber);
});
})
<div class="mybuttons">
<button id="mapOne" data-toggle="modal" data-target="#map-1-scene-1">Scene</button>
<button class="no-click-span" id="mapOneCurrent" data-toggle="modal" data-target="#map-1-scene-1"><i class="fas fa-charging-station fa2x"></i>Current</button>
</div>
However, you could simplify it by using "delegated event listening" to:
var mapNumber;
document.querySelector('.mybuttons').addEventListener('click',function(ev){
if (ev.target.tagName==="BUTTON") {
window.mapNumber = ev.target.id.replace("Current","");
console.log(mapNumber);
}
})
<div class="mybuttons">
<button id="mapOne" data-toggle="modal" data-target="#map-1-scene-1">Scene</button>
<button class="no-click-span" id="mapOneCurrent" data-toggle="modal" data-target="#map-1-scene-1"><i class="fas fa-charging-station fa2x"></i>Current</button>
</div>
In this snippet the event is listening to clicks on the wrapper container .mybuttobs but will trigger actions only if an inside BUTTON was clicked.

Unable to find the specific items value jQuery

I am facing an easy problem but unable to find a solution the problem is
i am creating a dynamic div with some elements also with some data
$("#divSearchedIssue").append(`
<div class="statistic d-flex align-items-center bg-white has-shadow">
<div class="icon bg-red">
<i class="fa fa-tasks"></i>
</div>
<div class="text">
***//want to get this below id value//**
Mobile Code :
<small id="mbCode">
${ data[0].MobileCode }
</small>
***/want to find/**
<br>
Failed From:
<small>
${ data[0].FailedStation }
</small>
<br>
Issues :
<small>
${ data[0].Issues }
</small>
</div>
<div class="text"><strong> </strong></div>
<div class="text">
<button type="button" id="btn" class="btn btn-warning pull-right">Start</button>
</div>
<div class="text"><br></div>
</div>`);
Here I have a button .On this button click i want to fetch the value of
small text which id is #mbCode as mentioned above inside the code
I am trying this by using the following button click code
$(document).on('click', '#btn', function () {
var data = $(this).closest('small').find('#mbCode').val();
alert(data);
});
but its not working.I mean I cant fetch the value of #mbCode on this button click .So help needed
Thanks for helping
Based on .closest()
Description: For each element in the set, get the first element that
matches the selector by testing the element itself and traversing up
through its ancestors in the DOM tree.
As <small> is not an ancestors to button in hierarchy(while traversing-up),
So You need to first go the parent of <small> through .closest() and then try to find <small> html using .find() and .html()
$(document).on('click', '#btn', function () {
var data = $(this).closest('.statistic').find('small').html();
alert(data);
});
Working snippet:-
data = [{'MobileCode':20,'FailedStation':'WATERLOO','Issues':'broken'}];
$("#divSearchedIssue").append('<div class="statistic d-flex align-items- center bg-white has-shadow"><div class="icon bg-red"><i class="fa fa-tasks"></i></div><div class="text">Mobile Code :<small id="mbCode">' + data[0].MobileCode + '</small><br>Failed From: <small> ' + data[0].FailedStation + '</small><br>Issues :<small> '+ data[0].Issues + '</small></div><div class="text"><strong> </strong></div><div class="text"><button type="button" id="btn" class="btn btn-warning pull-right">Start</button></div><div class="text"><br></div></div>');
$(document).on('click', '#btn', function () {
var data = $(this).closest('.statistic').find('small').each(function(){
alert($(this).html());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divSearchedIssue"></div>
Note:- .text() will work too
https://jsfiddle.net/tyz4ox50/
As identifiers must be unique, Directly use ID Selector with .text()/.html() method
var data = $('#mbCode').text()
However if you are appending multiple elements I would recommend an alternative to persist Mobile code arbitrary data using custom data-* attribute along with <button> which can be fetched using .data(key) and attach event handler using Class Selector
$("#divSearchedIssue").append('<button type="button" id="btn" class="btn btn-warning pull-right" data-mobilecode="' + data[0].MobileCode + '" >Start</button>');
var counter = 0;
function append() {
$("#divSearchedIssue").append('<button type="button" id="btn" class="btn btn-warning pull-right" data-mobilecode="' + ++counter + '" >Start</button>');
}
append();
append();
append();
$(document).on('click', '.btn', function() {
var data = $(this).data('mobilecode');
console.log(data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divSearchedIssue"></div>
Try the following code snippet
var value = $('#mbCode').val();
Make sure the id is unique
Ids shouldn't be duplicate in an web-page.
Also, small is not one of the parent nodes of btns, and use html instead of val.
You need to go two-level higher to statistic Make it
$(document).on('click', '.text #btn', function () {
var data = $(this).closest('.statistic').find('#mbCode');
console.log(data.html());
});
Demo
var counter = 0;
function append() {
$("#divSearchedIssue").append(
`<div class="statistic d-flex align-items-
center bg-white has-shadow">
<div class="icon bg-red"><i class="fa fa-tasks">
</i></div>
<div class="text">
Mobile Code :<small id="mbCode">` +
(counter++) +
`</small><br>Failed From: <small> ' +
data[0].FailedStation + '</small><br>Issues :<small> ' + data[0].Issues +
'</small></div>
<div class="text"><strong> </strong>
</div>
<div class="text"><button type="button" id="btn" class="btn btn-
warning pull-right">Start</button></div>
<div class="text"><br></div>
</div>`
);
}
append();
append();
append();
$(document).on('click', '.text #btn', function () {
var data = $(this).closest('.statistic').find('#mbCode');
console.log(data.html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divSearchedIssue"></div>
If your element already has an ID attribute you should be able to find the element by the ID. $("#mbCode")
Your js code
$(this).closest('small').find('#mbCode').val(); // "$(this)", in your code, represents the "button" that was clicked.
is looking for "small" tag inside "button" element, but it's not there. It would work if your button was like
<button type="button" id="btn" class="btn btn-warning pull-right"><small id="mbCode"></small></button>
This should work:
$(document).on('click', '#btn', function () {
var $mbCode = $('#mbCode');
console.log($mbCode);
});

Laravel ajax model to show posts

I have a foreach() from database table, I want to show a popup/model to show its extra information.
I am showing just title and description and on click i want to open up a popup and show its extra information.
#foreach($myProjects as $project)
<div class="col-sm-4 col-md-4 notes notes--blue">
<a href="#edit-note" data-toggle="modal" style="background-color: #f9f9f9;border-bottom: 5px solid #42A5F5">
<div class="notes__title">{{$project->title}}</div>
<div class="notes__body">{{$project->description}}</div>
</a>
<div class="notes__actions" data-demo-action="delete-listing">
<i class="zmdi zmdi-delete"></i>
</div>
<div class="notes__actions1" data-demo-action="delete-listing">
<i class="zmdi zmdi-edit"></i>
</div>
<div class="notes__actions2" data-demo-action="delete-listing">
<i class="zmdi zmdi-eye"></i>
</div>
</div>
#endforeach
I am completely blank, Should i fetch post id to a hidden html tag and on model button click an ajax call will fetch the record info based on the id ?
I would add a data-id attribute to one of the elements, possibly the wrapper, then add something like
$(document.body).on('click', '.clickable_element', function(e){
if ($(this).data('id')) {
$.ajax({
url : 'your detail url',
data: { id: parseInt( $(this).data('id'), 10 ),
success : function(response){
// open popup and add response into it.
}
})
}
});
Update
I just noticed you already have bootstrap modal there.
you can add your data-id to data-toggle element then in javascript
$('[data-toggle=modal]').on('shown.bs.modal' , function(){
// do your ajax stuff
// add response in `.modal-body`
})

angularJS : disable link based on variable value, and display message box

I am struggling to figure out how to disable a ng-click event based on the value of a boolean variable.
I have a form, on which the user has to click a (+) sign/ link to add a new record, when the user does this, a small function is triggered, and sets a boolean to false.
Code:
vm.addNewRecord = function (formClass) {
vm.hasID = false;
};
The form has an icon/ link that allows the user to save information about participant, to the record.
Code:
<div class="icon">
<a ng-click="addParticipants(data)">
<i class="fa fa-fw fa-plus"></i>
</a>
</div>
That issue is that this information depends on a record id, but this id does not exist yet.
I need to be able to disable the ng-click of: addParticipants(data) is the value of hasId = false, and at the same time (somehow) allow the user to click it to display a message in the lines of: "Please save this record before adding participants."
What I have tried so far, and without success:
<div class="datagrid-icon">
<a ng-click="datagrid.add(datagrid)" ng-disabled="!hasID">
<i class="fa fa-fw fa-plus"></i>
</a>
</div>
And:
<div class="datagrid-icon">
<a ng-click="datagrid.add(datagrid)" ng-class="{'disabled': !hasID}">>
<i class="fa fa-fw fa-plus"></i>
</a>
</div>
I checked the value of hasID and it is false but I am still able to click on the (+) sign for addParticipants. And also, I am not sure how if I manage to disable the click, I am going to display the message instructing the user to first save the main record and then adding participants will be possible.
If anyone could offer some help to resolve this, that would be much appreciated.
Thank you.
To disable a link you can do like
<a ng-click="hasID && datagrid.add(datagrid)">
<i class="fa fa-fw fa-plus"></i>
</a>
But it's much better to have a method inside your controller like
vm.addToGrid = function(id) {
if (id) {
$scope.datagrid.add(id);
} else {
alert('Save the record before');
}
}
<a ng-click="vm.addToGrid(datagrid)">
<i class="fa fa-fw fa-plus"></i>
</a>

Categories