voting with javascript - form.onsubit - javascript

I'm making a website for my school (I'm 16 years old) and I need that when I submit a form, it can change things within the form itself.
I tried to do something using "this", but it didn't work. Can someone help me?
HTML
<form class="form-votacao" name="form-votacao">
<div class="participant-box">
<img src="../images/blank.png" alt="blank" />
<p id="name">participant name undefined</p>
<p id="category">participant category undefined</p>
<p id="talent-info">talent info undefined</p>
<input
type="submit"
value="VOTAR"
name="vote-button"
id="vote-button"
/>
</div>
</form>
JAVASCRIPT
var form_votacao = document.forms["vote-form"];
form_votacao.onsubmit = function (event) {
let fundo = this.querySelector(".participant-box")
fundo.style.background = "green"
};
As there will be several divs with the ".participant-box" class inside the form, I would like you to change only the div that I click on the submit button

First, I changed the button's type as button, because if you make its type as submit, then the form will be submitted, hence the javascript will be useless.
Below is the code using javascript to change the background of the parent div by clicking the button inside it.
Please click on the Run code snippet button for the demo.
const buttons = document.querySelectorAll('.vote-button');
buttons.forEach(button => {
button.addEventListener('click', function() {
this.parentElement.style.backgroundColor = 'green';
});
});
<form class="form-votacao" name="form-votacao">
<div class="participant-box">
<p id="name">participant name undefined</p>
<p id="category">participant category undefined</p>
<p id="talent-info">talent info undefined</p>
<input
type="button"
value="VOTAR"
name="vote-button"
id="vote-button"
class="vote-button"
/>
</div>
<br/><br/>
<div class="participant-box">
<p id="name">participant name undefined</p>
<p id="category">participant category undefined</p>
<p id="talent-info">talent info undefined</p>
<input
type="button"
value="VOTAR"
name="vote-button"
id="vote-button"
class="vote-button"
/>
</div>
<br/><br/>
<div class="participant-box">
<p id="name">participant name undefined</p>
<p id="category">participant category undefined</p>
<p id="talent-info">talent info undefined</p>
<input
type="button"
value="VOTAR"
name="vote-button"
id="vote-button"
class="vote-button"
/>
</div>
</form>
I hope I understood your situation.

Related

How can I set some values using currentTarget with jQuery from different HTML elements?

Can anyone give me a hand with this?
I am trying to obtain different values depending which button is clicked and assign it into a variable.
A friend told me to add the values in an input to later by extracted by e.currentTarget but I was unable to make it work.
HTML:
<div class="curso-contenedor">
<div class="curso">
<input id="precio" value='12000' hidden>
<input id="cursoNombre" value='Web Developer' hidden>
<form><button class="btn-curso web-developer" id="webDeveloper">Agregar</button></form>
</div>
<div class="curso">
<input id="precio" value='13000' hidden>
<input id="cursoNombre" value='Marketing Digital' hidden>
<form><button class="btn-curso marketing-Digital" id="marketinDigital">Agregar</button></form>
</div>
</div>
jQuery:
$('.btn-curso').click(function(e){
let curso = {'precio': e.currentTarget('#precio'), 'curso': e.currentTarget('#cursoNombre')};
localStorage.setItem('datosCurso', JSON.stringify(curso));
e.preventDefault()
});
If anyone knows how to do this it would mean the world if you can help me since I have been trapped with this for days now trying different things.
Try this:
HTML
<div class="curso-contenedor">
<div class="curso">
<input name="precio" value='12000' hidden>
<input name="cursoNombre" value='Web Developer' hidden>
<button class="btn-curso web-developer" id="webDeveloper">Agregar</button>
</div>
<div class="curso">
<input name="precio" value='13000' hidden>
<input name="cursoNombre" value='Marketing Digital' hidden>
<button class="btn-curso marketing-Digital" id="marketinDigital">Agregar</button>
</div>
</div>
JQuery:
$('.curso-contenedor').on('click', '.curso', function(e){
let curso = {
'precio': $(e.currentTarget).find('input[name=precio]').val(),
'curso': $(e.currentTarget).find('input[name=cursoNombre]').val()
};
localStorage.setItem('datosCurso', JSON.stringify(curso));
e.preventDefault()
});
You should add delegate event listener to parent element
For more information: https://api.jquery.com/on/

How can I call a function multiple times from different buttons?

I am building a quiz page using javascript, and want the user to select from a multiple choice and then hit 'Go' to check their answer. Here is the html for the first question:
<p class="question">What is the name of Joey's bedtime penguin pal?</p>
<div class="radio">
<div>
<input type="radio" class="wrong" name="q1">Maurice
</div>
<div>
<input type="radio" class="wrong" name="q1">Clunkers
</div>
<div>
<input type="radio" class="right" name="q1">Hugsy
</div>
<div class="button">
<button type="button" class="go">Go</button>
</div>
<div>
<img src="images/hugsy.jpg" class="image" style="display: none;"
</div>
I have created a function which is called by the Go button which informs the user if they are right or not. Here is the javascript:
let go = document.querySelector('.go');
let correct = document.querySelector('.right');
let showPic = document.querySelector('img');
let remGo = document.querySelector('button');
let choices = document.querySelector('.radio');
let score = 0;
go.addEventListener('click', checkAnswer);
function checkAnswer() {
if (correct.checked) {
showPic.classList.remove('image');
remGo.remove();
choices.innerHTML = '<h2 style="color: green;">Correct!</h2>';
score++;
} else {
remGo.remove();
choices.innerHTML = '<h2 style="color: red;">Incorrect</h2>';
}
}
This code works the way I want it to but only for the first question. When I try to call the function again by clicking 'Go' on question 2 nothing happens.
Is there a way to call a function multiple times using different buttons?
document.querySelector('.go');
only selects the first matching element.
To select all elements with the .go class you need to use querySelectorAll
Then you'll need to assign your event listener to all elements returned.
Here is a minimal example:
let buttons = document.querySelectorAll('.go');
for (const button of buttons) {
button.addEventListener('click', checkAnswer);
}
function checkAnswer() {
console.log("checkingAnswer...")
}
<div class="button">
<button type="button" class="go">Go</button>
</div>
<div class="button">
<button type="button" class="go">Go</button>
</div>
<div class="button">
<button type="button" class="go">Go</button>
</div>
Thanks to those who helped. I have solved my issue now using jquery. This was the code I used:
$(".container").on("click", "button", function (e) {
var container = $(e.target).closest(".container");
if ($(container).find("input:checked").hasClass("right")) {
$(container).find("img").show();
$(container).find("button").remove();
$(container).find(".radio").html('<h2 style="color: green;">Correct!</h2>');
score++;
} else {
$(container).find(".radio").html('<h2 style="color: red;">Incorrect</h2>');
}
});

GTM - Table - Click on a button, and get the text of another selector

I am not a developer but I am trying to get hand in hand with Google Tag Manager.
I am working for some people that they want to track a button click on a search result.
So, you'd get the 10 products, with the name, description and a Sample button.
I can track the button on GTM (that's the easy bit), but I need to assign the button click to each product name.
This is the bit of HTML that I want to work on:
<tr>
<td>
<p class="category">
Product
</p>
<a href="/sector/product/123456789"><img class="search_image" src="https://example.com/medium/123456789.jpg" alt="Name of the Product" onerror="this.src='system/images/company_logo_block.jpg'" />
</a>
</td>
<td>
<h3>Name of the product</h3>
<p>Benefits of the product explained</p>
<p>Material <b>Plastic</b></p>
<div class="button_container">
<div class="action_container">
<div class="action_trigger">
<input type="hidden" id="code_123456789" name="code" value="123456789" />
<label class="visible" for="quantity_123456789">Quantity</label><br />
<input class="search_result_quantity numeric_only" id="quantity_123456789" name="quantity" type="number" value="1"
onkeydown="return isValidInput(this, 5, event);"/>
<label for="add_to_basket_123456789">Add to basket</label>
<input class="add_sample search_result_action" id="add_to_basket_123456789" name="add_to_basket" type="submit" value="Add to basket" />
</div>
<div class="action_response">
<img src="/sector/system/images/loading.gif" alt="Loading" />
</div>
<div class="action_result">
<img src="/sector/system/images/tick.jpg" alt="Success" /><span>Added.</span>View basket
</div>
<label for="get_sample">Get a Sample</label><input class="add_sample search_result_action" name="Sample_product" type="button" value="Sample Product" onclick="window.location='http://www.samplepage.com/123456789';"/>
<div class="clearer"></div>
</div>
</div>
<br/>
<p123456789</p>
<p>
Online
| 24/09/2015
</p>
<p><strong>Price: £26.99 +VAT</strong></p>
</td>
</tr>
So, when a user clicks on the button "Sample Product", I would like to grab the name of the product, which sits on the top <tr> with the tag h3.
For each product, there is a <tr> where all the information sits
On the console, I can get the "nodes" with document.querySelectorAll ("tr td h3)[0] - or [1] or [2] according to the name of the product I want.
I now can't get a function that, onClick a Button, will return me the <h3> text of that <tr> selector. Is this even possible?
Thanks so much for your help.
George
Ok. After long hours of trial and error, I came up with a solution that works.
I'll leave it here in case it might help someone.
function() {
var els = document.querySelectorAll('[value="Sample Product"]');
for (var i = 0; i < els.length; i += 1) {
if (els[i] === {{Click Element}}) {
var elsname = document.querySelectorAll('tr td h3')[i].innerText
return elsname; }
}
return elsname;
}

Unable to attach Event to an Submit button in a form

On the following page "https://www.capgemini.com/new-ways-to-accelerate-innovation". there are multiple sections with "Expand" button and when you click on expand button a form gets exposed. the issue here is am not able to attach click event to the "Submit" button.
I have tried using addeventlistener but the event is not getting assigned.
How do I do that, please advise.
https://www.capgemini.com/new-ways-to-accelerate-innovation
Expand Button is in the below code.
<div class="exp_article-header-bg">
<div class="exp_article-header-inner">
<h2 class="exp_article-header-title">TechnoVision 2017</h2>
<div class="exp_article-header-author"></div>
<div class="exp_article-header-lead">
<p>
TechnoVision 2017 gives you a framework to create a new digital story to solve problems and grasp new opportunities. Our 37 technology building blocks will help you to navigate the technology maze and give a clear direction to your business.
</p>
</div>
<div class="exp_article-header-expand">
**
<div class="exp_link exp_link--white exp_link--expand">
<span class="exp_link-label">EXPAND</span>**
<span class="exp_button-arrow exp_button-arrow--down"></span>
</div>
</div>
</div>
</div>
Form gets exposed when you click the above Expand button. The Submit button is in the form as highlighted below.
<form accept-charset="UTF-8" method="post" action="https://go.pardot.com/l/95412/2017-08-09/2tfbfg" class="form" id="pardot-form">
<style type="text/css">
form.form p label {
color: #000000;
}
</style>
<p class="form-field email pd-text required ">
<label class="field-label" for="95412_59459pi_95412_59459">Email Address</label>
<input type="text" name="95412_59459pi_95412_59459" id="95412_59459pi_95412_59459" value="" class="text" size="30" maxlength="255" onchange="piAjax.auditEmailField(this, 95412, 59459, 44072473);">
</p>
<div id="error_for_95412_59459pi_95412_59459" style="display:none"></div>
<p style="position:absolute; width:190px; left:-9999px; top: -9999px;visibility:hidden;">
<label for="pi_extra_field">Comments</label>
<input type="text" name="pi_extra_field" id="pi_extra_field">
</p>
<!-- forces IE5-8 to correctly submit UTF8 content -->
<input name="_utf8" type="hidden" value="☃">
<p class="submit">
<input type="submit" accesskey="s" value="Submit Now">
</p>
<script type="text/javascript">
//<![CDATA[
var anchors = document.getElementsByTagName("a");
for (var i = 0; i < anchors.length; i++) {
var anchor = anchors[i];
if (anchor.getAttribute("href") && !anchor.getAttribute("target")) {
anchor.target = "_top";
}
}
//]]>
</script>
<input type="hidden" name="hiddenDependentFields" id="hiddenDependentFields" value="">
</form>
Have CSS display:none; for the element which needs to be expanded. when expand is clicked call a javascript function which checks if the element is hidden , if hidden change the CSS display: block;.
Check the below working code.
<body>
<div class="exp_article-header-bg">
<div class="exp_article-header-inner">
<h2 class="exp_article-header-title">TechnoVision 2017</h2>
<div class="exp_article-header-author"></div>
<div class="exp_article-header-lead"><p>TechnoVision 2017 gives you a framework to create a new digital story to
solve problems and grasp new opportunities. Our 37 technology building blocks will help you to navigate the
technology maze and give a clear direction to your business.</p>
</div>
<div class="exp_article-header-expand">
**
<div class="exp_link exp_link--white exp_link--expand">
<button onclick="myFunction()" class="exp_link-label">EXPAND</button>
**
<span class="exp_button-arrow exp_button-arrow--down" id="expandDiv"
style="color: #000066; background-color: gainsboro;display: none;">I Got Expanded</span></div>
</div>
</div>
</div>
</body>
Javascript function:-
<script>
function myFunction() {
var x = document.getElementById('expandDiv');
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
</script>
check on plnkr: https://plnkr.co/edit/MWKYxmV6Jk2eId3Owt2u?p=preview
where is ur form opening? if u're usingjquery, just target the form id and do .submit()
You're going to want to use the 'onsubmit' event listener, most likely with a preveninstead of a click event.
document.querySelector("#submit-button").addEventListener("submit", function(event) {
//your stuff here
event.preventDefault();
}, false);

pass values from separate divs into a javascript function

I have a form that has three separate divs within it.
<form method="post">
<div id = "f1">
<div class="label">Value 1:</div>
<input type="text" name="name"/>
<button id = "next1" type="button" onclick="checkValue()">Next</button>
</div>
<div id ="f2">
<div class="label">Value 2:</div><br>
<input type="text" name="name"/>
<button type="button" onclick="checkValue()">Next</button><br>
</div>
<div id ="f3">
<div class="label">Value 3:</div><br>
<input type="text" name="name"/>
<button type="button" onclick="checkValue()">Next</button><br>
</div>
</div>
</form>
In my javascript function. I have a fadein and fadeout attached to each div when the next button is pressed. When the "next1" button is pressed the first div will be faded out and the second div will fade in. I want to check the values inputted in the first div when the user presses the first next button. I know how to do this if i just passed in the whole form into my javascript function on the final submit button, but I would like to know how to do this after each next button is pressed.
I also will have more than one value in each of the divs (f1, f2, f3) but for simplicity I only included one value.
EDIT*: further explaintaion
If i did this by passing in the form into checkValue. I could just do an onsubmit = "checkValue()". And then in my JS file, I would just include checkValue(form) as its parameter. If i want to do a check after every single button is pressed, I am not sure how to do this or what to pass in as its parameter.
Simple mock up hopefully to get you one your way.
Fiddle: http://jsfiddle.net/AtheistP3ace/krr3tgLx/1/
HTML:
<form method="post">
<div id="f1" style="display: block;">
<div class="label">Value 1:</div>
<input type="text" name="name" />
<button id="next1" type="button" onclick="checkValue(this)">Next</button>
</div>
<div id="f2">
<div class="label">Value 2:</div>
<br>
<input type="text" name="name" />
<button type="button" onclick="checkValue(this)">Next</button>
<br>
</div>
<div id="f3">
<div class="label">Value 3:</div>
<br>
<input type="text" name="name" />
<button type="button" onclick="checkValue(this)">Next</button>
<br>
</div>
</div>
</form>
JS:
function checkValue (button) {
// Finds the sibling input of the button
var input = $(button).siblings('input');
// Gets input value
var value = input.val();
// Stops showing next div if no value
if (value == '') {
return false;
}
else {
// Finds the parent div holding button and input
var div = $(button).closest('div');
// Fades out current div
div.fadeOut();
// Gets next div and fades it in
div.next().fadeIn();
}
}
CSS:
form > div {
display: none;
}
From my assumptions this is what you are looking for :
Multipart form handler
Basically I wired up each button with a class
<button id = "next1" type="button" class="check-btn">Next</button>
Then I used Jquery to get all those buttons and find the parent div (based on your structure) and then get all the child inputs (can include selects etc). From here you can continue to tweak to perform a check on each type of input etc.
$(document).ready(function(){
$('.check-btn').on('click',function(){
var parent = $(this).parent('div');
var elems = parent.find('input');
alert(elems.length);
//DO checks here for each element
});
});

Categories