Iterate throughout div using jQuery - javascript

I have a button, I need to get a status i.e. to check weather its male or female, below is my code.
<!-- GENDER BUTTON -->
<div class="btn-group gender_guest" tabindex="0">
<a class="btn active btn-default btn-success gender" onclick="genderClicked(this,'female${status.index}')" id="male${status.index}">Male</a>
<a class="btn btn-default gender" onclick="genderClicked(this,'male${status.index}')" id="female${status.index}">Female</a>
</div>
My script
function genderClicked(clickedObj, id) {
$('#' + id).removeClass("active");
$('#' + id).removeClass("btn-success");
$(clickedObj).addClass("active");
$(clickedObj).addClass("btn-success");
}
This script works fine,its purpose is to just change color.I need another method to know which gender is selected...
Inside my JavaScript page I need to set in to a variable what is the gender, my onclick and id is used to pass the value to change the color when it gets clicked.So without touching that I need to set the value to that variable.

Since you are using jQuery, use the class selector to add an event.
I commented the JS, to explain what it does.
$('.gender').on('click', function(e) {
// prevent that the anchor is triggered
e.preventDefault();
// remove the classes from a links
$('.gender_guest a').removeClass('active btn-success');
// add the classes to the clicked one
$(this).addClass('active btn-success');
// get the gender */
var gender = $(this).attr('id');
// returns male.... or female...
});
/* only for demonstration */
.active{ border: 2px solid blue }
.btn-success { color: green; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- GENDER BUTTON -->
<div class="btn-group gender_guest" tabindex="0">
<a class="btn active btn-default btn-success gender" id="male${status.index}">Male</a>
<a class="btn btn-default gender" id="female${status.index}">Female</a>
</div>

function genderClicked(clickedObj, id) {
..
var gender = "male";
if( id == "female${status.index}" ){
gender = "female";
}
console.log(gender);
}

Related

document.getElementById() not working as intended with multiple ids

I have an issue with document.getElementById(). Basically I have different forms each one with a different id and I'm using a bit of Javascript to replace some classes and add dinamically file name after upload.
That should be really easy, but I don't know why even if the ids are totally unique I get a weird behavior: whatever is the form in which I submit a file javascript will apply changes always on the first of them.
function spinnerLoad(){
document.getElementById('file-name[[${id}]]').textContent = this.files[0].name;
document.getElementById('spinner[[${id}]]').classList.replace('fas', 'spinner-border');
document.getElementById('spinner[[${id}]]').classList.replace('fa-file-upload', 'spinner-border-sm');
document.getElementById('uploadForm[[${id}]]').submit()
}
/*I'm using Bootstrap for my styling rules*/
/*${id} variable is server-side and it's there to make unique each form, I'm using Thymeleaf template engine*/
<form th:id="'uploadForm'+${id}" method="post" enctype="multipart/form-data" th:action="#{/upload/{id} (id=${id})}">
<label for="file-upload" class="btn btn-outline-success">
<span th:id="'spinner'+${id}" class="fas fa-file-upload"></span> <b>Upload file:</b> <i th:id="'file-name'+${id}">No file selected</i>
</label>
<input id="file-upload" type="file" name="multipartFile" accept="application/pdf" style="display: none" th:onchange="spinnerLoad()"/>
</form>
I googled the problem but I didn't manage to find a specific answer to my issue, so that's why I'm here bothering you.
I hope someone can help my figure this out, thank you.
You get a lot of repeating code and that can be hard to maintain. Here I placed the event listener on the the parent <div> to all the buttons. Then I need to test if is a button. And there is no need for an id for each button.
Actually, if you are just replacing a class name you don't even need to do the test (if()), because replace() will only do the replacement when the old value is present. This should be fine:
buttons.addEventListener('click', e => {
e.target.classList.replace('btn-success', 'btn-danger');
});
But here is the full example with the test:
var buttons = document.getElementById('buttons');
buttons.addEventListener('click', e => {
if (e.target.nodeName == 'BUTTON') {
e.target.classList.replace('btn-success', 'btn-danger');
}
});
.btn-success {
background-color: green;
}
.btn-danger {
background-color: red;
}
<div id="buttons">
<button class="btn-success">Button 1</button>
<button class="btn-success">Button 2</button>
<button class="btn-success">Button 3</button>
</div>
You're missing the css that would make this work, but otherwise your example is functional. However, it can be done more simply by working on the buttons as a class instead of individually.
var btns = document.getElementsByClassName("btn");
var addDanger = function(){
this.classList.replace('btn-success', 'btn-danger')
};
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener('click', addDanger, false);
};
.btn {height:20px; width: 50px;}
.btn-success {background-color:green}
.btn-danger {background-color:red}
<button id="btn1" class="btn btn-success"></button>
<button id="btn2" class="btn btn-success"></button>
<button id="btn3" class="btn btn-success"></button>

Hide&Show Fieldset on Javascript using a button doesn't work on first click / How to change button title on click

I am trying to hide/sow a fieldset using a button, which works like a charm. However it doesn't wonk when I click the first time, but from the second time on it keeps working ok.
How can I make work the first time I click the button.
Also I'd ike to change the button's title on click too, but I don't know how.
Thanks in advance!
This is the code I have:
$(document).ready(function() {
$('#OcultarEncabezadoFactura').click(function() {
var fieldset = document.getElementById("fsEncabezado");
var boton = document.getElementById("OcultarEncabezadoFactura");
if (boton.textContent== "Ocultar Encabezado") {
$('#fsEncabezado').hide();
boton.textContent= "Mostrar Encabezado";
//title I would like the button to have when fieldset is hidden
} else {
$('#fsEncabezado').show();
boton.textContent= "Ocultar Encabezado";
//title I would like the button to have when fieldset is shown
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" name="btnOcultarEncabezadoFactura" class="btn btn-xs btn-primary" id="OcultarEncabezadoFactura" data-row-id="0">Ocultar Encabezado</button>
<fieldset id="fsEncabezado"></fieldset>
A button element doesn't have a title property so your test was failing. You need to check the button's textContent.
Also, don't use HTML comment syntax (<!-- comment -->) inside of <script> tags. To comment in JavaScript, it's: // comment here.
$(document).ready(function(){
$('#OcultarEncabezadoFactura').click (function(){
var fieldset = document.getElementById("fsEncabezado");
var boton= document.getElementById("OcultarEncabezadoFactura");
if(boton.textContent =="Ocultar Encabezado"){
fieldset.classList.add('hide');
boton.textContent ="Mostrar Encabezado";
} else {
fieldset.classList.remove('hide');
boton.textContent="Ocultar Encabezado";
}
});
});
.hide { display:none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" name="btnOcultarEncabezadoFactura" class="btn btn-xs btn-primary" id="OcultarEncabezadoFactura" data-row-id="0">Ocultar Encabezado</button>
<fieldset id="fsEncabezado"></fieldset>
But, if your goal is to have a button that simply toggles the visibility of the fieldset, just use the element.classList.toggle() API:
$(document).ready(function(){
var fieldset = document.getElementById("fsEncabezado");
$('#OcultarEncabezadoFactura').click (function(){
fieldset.classList.toggle("hide");
});
});
.hide { display:none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" name="btnOcultarEncabezadoFactura" class="btn btn-xs btn-primary" id="OcultarEncabezadoFactura" data-row-id="0">Ocultar Encabezado</button>
<fieldset id="fsEncabezado"></fieldset>
You should use innerHTML to change the text on your button, not title.
$(document).ready(function() {
$('#OcultarEncabezadoFactura').click(function() {
var fieldset = document.getElementById("fsEncabezado");
var boton = document.getElementById("OcultarEncabezadoFactura");
if (boton.innerHTML == "Ocultar Encabezado") {
fieldset.classList.add('hide');
boton.innerHTML = "Mostrar Encabezado";
<!-- title I would like the button to have when fieldset is hidden-->
} else {
fieldset.classList.remove('hide');
boton.innerHTML = "Ocultar Encabezado";
<!-- title I would like the button to have when fieldset is shown-->
}
});
});
.hide {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" name="btnOcultarEncabezadoFactura" class="btn btn-xs btn-primary" id="OcultarEncabezadoFactura" data-row-id="0">Ocultar Encabezado</button>
<fieldset id="fsEncabezado">
<input type="text" />
</fieldset>

How to toggle show and hide for two forms present in the same div?

I have two forms present in a div, form1 is visible when the page loads, and if I click the next button form1 is hidden and form2 is shown, which is working as expected.
Now I want to achieve the reverse of above scenario which is on click of a back button, form2 should be hidden and form 1 is shown.
Here's javascript code I have so far..
function switchVisible() {
document.getElementById("disappear").innerHTML = "";
if (document.getElementById('newpost')) {
if (document.getElementById('newpost').style.display == 'none') {
document.getElementById('newpost').style.display = 'block';
document.getElementById('newpost2').style.display = 'none';
} else {
document.getElementById('newpost').style.display = 'none';
document.getElementById('newpost2').style.display = 'block';
}
}
}
So basically I am looking for a way to achieve toggle functionality for two forms present in the same div using javascript and setting their display property.
Use a variable stepCount and then according to the value of count display appropriate form.
Like initialise the stepCount with 0, then on click of next increment it by 1 and check condition if stepCount is 1 show second form
Similarly from there if back button is pressed decrement the stepCount by 1 and check condition if stepCount is 0 show first form
Do all this on click of appropriate button click event
Make two button elements
<button id="next"></button>
<button id="back"></button>
You can use jquery (or plain javascript) for this, but I personally prefer jquery.
$("#next").click(function {
$("#newpost").hide();
$("#newpost1").show();
});
$("#back").click(function {
$("#newpost").show();
$("#newpost1").hide();
});
(Here 'newpost' and 'newpost1' are the id's of the two form elements)
You can use a similar format if you want to use plain javascript.
Add this
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</head>
You can also use link button and provide URL for particular form in this and hide back link button when click on back that time show only Next button.
e.g.
Next
Previous
$("#btnNext").click(function {
$("#btnNext").hide();
$("#btnPrevious").show();
});
$("#btnPrevious").click(function {
$("#btnPrevious").show();
$("#btnNext").hide();
});
You can use toggle function to show hide div.
$('#newpost2').hide();
$("#Toggle").click(function() {
$(this).text(function(i, v) {
return v === 'More' ? 'Back' : 'More'
});
$('#newpost, #newpost2').toggle();
});
.one {
height: 100px;
width: 100px;
background: #eee;
float: left;
}
.two {
height: 100px;
width: 150px;
background: #fdcb05;
float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='Toggle' class='pushme'>More</button>
<div class="one" id='newpost'>
<p>Show your contain</p>
</div>
<div class="two" id='newpost2'>
<p>Hide your contain</p>
</div>
This fiddle for button disappear:
$("#next").click(function()
{
$("#next").hide();
$("#back").show();
});
$("#back").click(function() {
$("#back").show();
$("#next").show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<input type="button" id="next" value="Next"/>
<input type="button" id="back" value="Back"/>
<button class="btn btnSubmit" id="Button1" type="button" value="Click" onclick="switchVisible();">NEXT</button>
<button type="button" class="btn btnSubmit" onclick="previousVisible();" >BACK</button>
simply use this jquery:
function switchVisible()
{
$("#newpost").hide();
$("#newpost2").show();
}
function previousVisible()
{
$("#newpost").show();
$("#newpost2").hide();
}
your updated fiddle
Or you may do like this:
<button class="btn btnSubmit" id="Button1" type="button" value="Click" onclick="form(1);">NEXT</button>
<button type="button" class="btn btnSubmit" onclick="form(2);" >BACK</button>
function form(a)
{
if(a==1)
document.getElementById("newpost").style.display="none";
else
document.getElementById("newpost2").style.display="block";
}

Button in div not working

Initially my div (with the button inside) is hidden, when I press a button I make 10 clones of that div.
I want to be able to use each of the buttons seperatly (they all have the same attributes and class). At the moment I cannot use the any of the buttons.
<div class="search-result">
<h3>Titel(year)</h3>
<button class="btn btn-warning btnFavorite">Favorite</button>
<button id="btnArkiv" class="btn btn-warning btnFAvorite">Arkiv</button>
</div>
$(".btnFavorite").on("click", function(){
alert("hej");
var input = $("#search").val();
saveFavorite(favoriteMovie);
});
Method to clone the div x times.
for(movie in search){
console.log(search[movie].Title);
favoriteMovie = search[movie].Title;
$(".search-result:first").clone().appendTo(".search").find('h3').text(search[movie].Title);
$('#your_element').attr('id','the_new_id');
}
I've replaced the input elements with actual buttons and delegated the event to the body, so that newly inserted movie buttons automatically use the same event handler. The div cloning function can also use some updates, but it should work and that's not the question. :)
You might have to update any function that uses the value as well, since it's a data-value attribute now. Hope it helps.
PS: I don't usually use jQuery, so untested and there might be syntax errors.
<div class="search-result">
<h3>Titel(year)</h3>
<button data-value="Favoritfilm" class="btn btn-warning btnFavorite">buttonText</button>
<button id="btnArkiv" data-value="Arkiv" class="btn btn-warning">buttonText</button>
</div>
$("body").on("click", ".btnFavorite", function() {
alert("hej");
var input = $("#search").val();
saveFavorite(favoriteMovie);
});
It seems that you are using click event without using the right ID.
$(".btnFavorite") here you need to use the right ID, which is related to the button you are going to activate. In this case "btnArkiv".
var movieList = [
{
'ID': 1,
'title': 'Movie 1',
'year': 1988
},
{
'ID': 2,
'title': 'Movie 2',
'year': 2017
}
];
$(".btnFavorite").on("click", function(){
alert("hej");
var input = $("#search").val();
saveFavorite(favoriteMovie);
});
$(".btnAdd").click(function() {
for(index in movieList){
$(".list").append("<div class='search-result' data-id=" + movieList[index].ID + "><h3>" + movieList[index].title + " (" + movieList[index].year + ")</h3><button class='btn btn-warning btnFavorite' data-action='favoritize-id-" + movieList[index].ID + "'>Favorite Movie " + movieList[index].ID + "</button></div>");
}
});
.search-result {
background-color: #EEE;
padding: 20px;
margin: 15px 0;
}
.search-result h3 {
display: inline-block;
}
.search-result button {
display: inline-block;
margin: 0 0 0 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn btn-warning btnAdd">Show Movie List</button>
<div class="list"></div>
According to the docs for .on this is why you are finding that only your first set of buttons work after cloning the result 10 times:
Event handlers are bound only to the currently selected elements; they must exist at the time your code makes the call to .on(). To ensure the elements are present and can be selected, place scripts after the elements in the HTML markup or perform event binding inside a document ready handler. Alternatively, use delegated events to attach event handlers.
You can read more about it here: http://api.jquery.com/on/.
Since there isn't much information to go on, one way you can make all of your buttons use the same event handler is by using event delegation as CBroe mentioned in the comments.
Check out the snippet I have here with all the buttons working.
$(".search").on("click", function(e) {
if ($(e.target).hasClass('btnFavorite')) {
alert('hej');
}
});
for (var i = 0; i < 10; i++) {
$(".search-result:first").clone().appendTo(".search");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="search">
<div class="search-result">
<h3>Titel(year)</h3>
<input type="submit" value="Favoritfilm" class="btn btn-warning btnFavorite">
<input id="btnArkiv" type="submit" value="Arkiv" class="btn btn-warning">
</div>
</div>
In the snippet, I put a listener on the parent container and then check that the clicked target is the correct button before alerting.

Clicking a button and detect its status in jquery

I am have a button like this:
<a class="btn btn-sm btn-danger employee" data-emp_id="23" href="javascript:void(0)" disabled>Resign</a>
If ajax response success it adds disabled to this button.
Here I need to this button has disabled on click event. If it has, need to alert different message, or if it hasn't I need to alert different message.
This is how I tried it.
$(document).on('click', 'a.employee', function(e){
var empID = $(this).data('emp_id');
if($(this).is(':disabled')) {
alert('message1');
} else {
alert('message2');
}
});
Also tried it something like this:
$(document).on('click', 'a.employee:not(:disabled)', function(e){
var empID = $(this).data('emp_id');
alert('here');
});
But, both are not working for me..
Hope somebody may help me out.
Thank you.
You cannot disable an anchor element, and adding a disabled attribute to it would mean that your HTML is invalid.
To solve this you could simply add a class to the element and key the click behaviour on that. Try this:
$(document).on('click', 'a.employee', function(e) {
e.preventDefault();
var empID = $(this).data('emp_id');
if ($(this).hasClass('disabled')) {
console.log('message1');
} else {
console.log('message2');
}
});
.disabled {
color: #CCC;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="btn btn-sm btn-danger employee disabled" data-emp_id="23" href="#">Disabled</a>
<a class="btn btn-sm btn-danger employee" data-emp_id="23" href="#">Not disabled</a>
Also note the use of preventDefault() instead of adding javascript: to the href attribute of the a element.
Disabled is not an attribute and hence not a property of anchor tag
try this way
$(document).on('click', 'a.employee[disabled])', function(e){
var empID = $(this).data('emp_id');
alert('here');
});

Categories