I'm having trouble handling multiple buttons to delete items on a cart page. I read about parentNode, operators delete, remove but none seem to work. Here's the code.
HTML:
<section id="cart__items">
<article class="cart__item" data-id="{product-ID}">
<div class="cart__item__img">
<img id ="image" alt="Photographie dun canapé">
</div>
<div class="cart__item__content">
<div class="cart__item__content__titlePrice">
<h2 class=title></h2>
<p class =price></p>
</div>
<div class="cart__item__content__settings">
<div class="cart__item__content__settings__quantity">
<p class= quantity>Qté : </p>
<input type="number" class="itemQuantity" name="itemQuantity" min="1" max="100" value="">
</div>
<div class="cart__item__content__settings__delete">
<p class="deleteItem">Supprimer</p>
</div>
</div>
</div>
</article>
JS:
let removeCart = Array.prototype.slice.call(document.getElementsByTagName('article'), 0);
for (let i = 0; i < removeCart.length; i++) {
let removeItems = (removeCart[i]);
console.log(removeItems)
let removeButton = document.getElementsByClassName('deleteItem');
for (let i = 0; i < removeButton.length; i++) {
removeButton[i].addEventListener("click", function (event) {
removeItems.remove(removeCart[i])
})
}
So as you can see, this allows me to delete entirety of the cart content. How could I set each buton to delete the article (and its localStorage) inside which they exist? If any of you could help that'd be great.
Snippet below makes use of event delegation
If you were to dynamically create all the cart items, manually attaching event listeners wouldn't be possible.
In order to handle LocalStorage update (not quite sure of its structure since you haven't provided anything) I assume you're utilizing some sort of product-id or data-id, so just filter out the id and set localstorage again.
// pass the id of item to be deleted
const updateCartLocalStorage = (cartItemId) => {
const currentCartLS = JSON.parse(localStorage.getItem('cart'));
const updatedCartLS = currentCartLS.filter(c => c.id !==
cartItemId);
localStorage.setItem('cart', JSON.stringify(updatedCartLS));
}
const cartItemsSection = document.querySelector('#cart__items');
const handleDeleteItem = (e) => {
// if user clicks on delete item, find and remove the parent article
if (e.target.classList.contains('deleteItem')) {
const parentArticle =
e.target.parentElement.parentElement.parentElement.parentElement;
console.log(parentArticle.dataset.id);
parentArticle.remove();
updateLocalCartLocalStorage(<id>);
} else {
return;
}
};
cartItemsSection.addEventListener('click', handleDeleteItem);
// alternative solution (to get rid of stacking .parentElement...)
const cartArticles = document.querySelectorAll('.cart__item');
const deleteCartItem = (e) => {
if (e.target.classList.contains('deleteItem')) {
const parent = e.currentTarget;
parent.remove();
updateLocalCartLocalStorage(<id>);
} else {
return;
}
};
cartArticles.forEach((article) => {
article.addEventListener('click', deleteCartItem);
});
<section id="cart__items">
<article class="cart__item" data-id="1" style="background-color: blue">
<div class="cart__item__img">
<img id="image" alt="Photographie dun canapé" />
</div>
<div class="cart__item__content">
<div class="cart__item__content__titlePrice">
<h2 class="title"></h2>
<p class="price"></p>
</div>
<div class="cart__item__content__settings">
<div class="cart__item__content__settings__quantity">
<p class="quantity">Qté :</p>
<input
type="number"
class="itemQuantity"
name="itemQuantity"
min="1"
max="100"
value=""
/>
</div>
<div class="cart__item__content__settings__delete">
<button class="deleteItem">Supprimer</button>
</div>
</div>
</div>
</article>
<article class="cart__item" data-id="2" style="background-color: red">
<div class="cart__item__img">
<img id="image" alt="Photographie dun canapé" />
</div>
<div class="cart__item__content">
<div class="cart__item__content__titlePrice">
<h2 class="title"></h2>
<p class="price"></p>
</div>
<div class="cart__item__content__settings">
<div class="cart__item__content__settings__quantity">
<p class="quantity">Qté :</p>
<input
type="number"
class="itemQuantity"
name="itemQuantity"
min="1"
max="100"
value=""
/>
</div>
<div class="cart__item__content__settings__delete">
<button class="deleteItem">Supprimer</button>
</div>
</div>
</div>
</article>
<article class="cart__item" data-id="3" style="background-color: green">
<div class="cart__item__img">
<img id="image" alt="Photographie dun canapé" />
</div>
<div class="cart__item__content">
<div class="cart__item__content__titlePrice">
<h2 class="title"></h2>
<p class="price"></p>
</div>
<div class="cart__item__content__settings">
<div class="cart__item__content__settings__quantity">
<p class="quantity">Qté :</p>
<input
type="number"
class="itemQuantity"
name="itemQuantity"
min="1"
max="100"
value=""
/>
</div>
<div class="cart__item__content__settings__delete">
<button class="deleteItem">Supprimer</button>
</div>
</div>
</div>
</article>
<article class="cart__item" data-id="4" style="background-color: yellow">
<div class="cart__item__img">
<img id="image" alt="Photographie dun canapé" />
</div>
<div class="cart__item__content">
<div class="cart__item__content__titlePrice">
<h2 class="title"></h2>
<p class="price"></p>
</div>
<div class="cart__item__content__settings">
<div class="cart__item__content__settings__quantity">
<p class="quantity">Qté :</p>
<input
type="number"
class="itemQuantity"
name="itemQuantity"
min="1"
max="100"
value=""
/>
</div>
<div class="cart__item__content__settings__delete">
<button class="deleteItem">Supprimer</button>
</div>
</div>
</div>
</article>
</section>
Related
i am creating a to-do list, i want the user to be able to edit and delete the added tasks, this will be possible by removing readonlyattribute from HTML. but i am struggling doing the edit function.
Here is my code:
const formulario=document.getElementById("new-task-form");
const lista=document.getElementById("list");
const input=document.querySelector("#new-task-input");
let id=0;
formulario.addEventListener('submit', (e)=>{
//console.log("activado");
e.preventDefault();
addTask();
});
let addTask=()=>{
id++;
let task=input.value;
lista.innerHTML+=`<div id="tasks">
<div class="task" id="taskin">
<div class="content" id="${id}">
<input
id="${id}"
type="text"
class="text"
value=${task}
readonly
/>
</div>
<div class="actions">
<button class="edit">Edit</button>
<button class="delete">Delete</button>
</div>
</div>
</div> `
input.value='';
}
lista.addEventListener('click', (evento)=>{
console.log(evento);
if(evento.target.className=="edit"){
console.log("Editar");
}else if(evento.target.className=="delete"){
console.log("Borrar");
}
})
<body>
<header>
<h1>Task List</h1>
<form action="#" id="new-task-form"> <!--Formulario para poner tareas-->
<input type="text" id="new-task-input" placeholder="Que vas a hacer" />
<input type="submit" id="new-task-submit" value="Add Task" />
</form>
</header>
<main>
<div id="list" class="task-list">
<h2>Tasks</h2>
<div id="tasks">
<!-- <div class="task">
<div class="content">
<input type="text"
class="text"
value="My Task"
readonly
/>
</div>
<div class="actions">
<button class="edit">Edit</button>
<button class="delete">Delete</button>
</div>
</div> -->
</div>
</div>
</main>
<script src="app.js"></script>.
</body>
</html>
Thanks in advance :D
I have added some lines to your JS code. Please check.
lista.addEventListener('click', (evento)=>{
let parentEl = evento.target.parentNode.parentNode;
let input = parentEl.getElementsByTagName('input');
if(evento.target.className=="edit"){
console.log("Editar");
input[0].removeAttribute('readonly');
}else if(evento.target.className=="delete"){
console.log("Borrar");
}
})
Test it in the Snippet below:
const formulario=document.getElementById("new-task-form");
const lista=document.getElementById("list");
const input=document.querySelector("#new-task-input");
let id=0;
formulario.addEventListener('submit', (e)=>{
//console.log("activado");
e.preventDefault();
addTask();
});
let addTask=()=>{
id++;
let task=input.value;
lista.innerHTML+=`<div id="tasks">
<div class="task" id="taskin">
<div class="content" id="${id}">
<input
id="${id}"
type="text"
class="text"
value=${task}
readonly
/>
</div>
<div class="actions">
<button class="edit">Edit</button>
<button class="delete">Delete</button>
</div>
</div>
</div> `
input.value='';
}
lista.addEventListener('click', (evento)=>{
let parentEl = evento.target.parentNode.parentNode;
let input = parentEl.getElementsByTagName('input');
console.log(input[0]);
if(evento.target.className=="edit"){
input[0].removeAttribute('readonly');
console.log("Editar");
}else if(evento.target.className=="delete"){
console.log("Borrar");
}
})
<body>
<header>
<h1>Task List</h1>
<form action="#" id="new-task-form"> <!--Formulario para poner tareas-->
<input type="text" id="new-task-input" placeholder="Que vas a hacer" />
<input type="submit" id="new-task-submit" value="Add Task" />
</form>
</header>
<main>
<div id="list" class="task-list">
<h2>Tasks</h2>
<div id="tasks">
<!-- <div class="task">
<div class="content">
<input type="text"
class="text"
value="My Task"
readonly
/>
</div>
<div class="actions">
<button class="edit">Edit</button>
<button class="delete">Delete</button>
</div>
</div> -->
</div>
</div>
</main>
<script src="app.js"></script>.
</body>
</html>
Hope it helps.
First, 2 elements have the same id 's value :
<div class="content" id="${id}"> and <input id="${id}">
You can change same as :
const formulario=document.getElementById("new-task-form");
const lista=document.getElementById("list");
const input=document.querySelector("#new-task-input");
let id=0;
formulario.addEventListener('submit', (e)=>{
//console.log("activado");
e.preventDefault();
addTask();
});
let addTask=()=>{
id++;
let task=input.value;
lista.innerHTML+=`<div id="tasks">
<div class="task" id="taskin">
<div class="content" id="${id}">
<input
id="input-${id}"
type="text"
class="text"
value=${task}
readonly
/>
</div>
<div class="actions">
<button class="edit" data-task_id="input-${id}">Edit</button>
<button class="delete" data-task_id="input-${id}">Delete</button>
</div>
</div>
</div> `
input.value='';
}
lista.addEventListener('click', (evento)=>{
if(evento.target.className=="edit"){
document.getElementById(evento.target.dataset.task_id).removeAttribute('readonly');
}else if(evento.target.className=="delete"){
document.getElementById(evento.target.dataset.task_id).remove();
}
})
<body>
<header>
<h1>Task List</h1>
<form action="#" id="new-task-form"> <!--Formulario para poner tareas-->
<input type="text" id="new-task-input" placeholder="Que vas a hacer" />
<input type="submit" id="new-task-submit" value="Add Task" />
</form>
</header>
<main>
<div id="list" class="task-list">
<h2>Tasks</h2>
<div id="tasks">
<!-- <div class="task">
<div class="content">
<input type="text"
class="text"
value="My Task"
readonly
/>
</div>
<div class="actions">
<button class="edit">Edit</button>
<button class="delete">Delete</button>
</div>
</div> -->
</div>
</div>
</main>
<script src="app.js"></script>.
</body>
</html>
Maybe you mean remove the readonly attribute on textbox inside the three divs?
$('.edit').click(function(){
$('.first_div input, .second_div input, .third_div input').removeAttr('readonly');
});
$('.edit_first').click(function(){
$('#first_textbox').removeAttr('readonly');
});
$('.edit_second').click(function(){
$('#second_textbox').removeAttr('readonly');
});
$('.edit_third').click(function(){
$('#third_textbox').removeAttr('readonly');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="first_div">
<input readonly id="first_textbox">
</div>
<div class="second_div">
<input readonly id="second_textbox">
</div>
<div class="third_div">
<input readonly id="third_textbox">
</div>
<button class="edit">Edit All</button>
<button class="edit_first">Edit first textbox</button>
<button class="edit_second">Edit second textbox</button>
<button class="edit_third">Edit third textbox</button>
I have a Component that causes an error, "TypeError: Cannot read property 'value' of null". It's nested inside of another component, and makes that component not load.
This is the code:
const NewItem = (props) => {
const qty = "QuantityBox" + props.identifier.toString();
const prc = "PriceBox" + props.identifier.toString();
return(
<div className="NewItem">
<div className="ItemNameInput">
<p className="InputLabel">Item Name</p>
<input className="inputFull" type="text" />
</div>
<div className="QuantityAndPrice">
<div className="QuantityInput">
<p className="InputLabel">Qty</p>
<input className="inputEighth" value="1" id={qty} type="text" />
</div>
<div className="PriceInput">
<p className="InputLabel">Price</p>
<input className="inputFourth" value="0" id={prc} type="text" />
</div>
<div className="TotalOutput">
<p className="InputLabel">Total</p>
<h4 className="TotalAmount">{(document.getElementById(qty).value * document.getElementById(prc).value).toFixed(2)}</h4>
</div>
<img src={TrashCan} alt="Delete" />
</div>
</div>
)
}
Right in the "TotalAmount" h4, is where the problem arises. If I remove that part, it loads up just fine. Judging from the error, it can't find the elements I'm specifying, but I don't understand why. I don't know if it has anything to do with the parent component, but I'll put it here just in case:
class NewInvoice extends Component {
constructor(props) {
super(props)
this.state = {
numberOfItems: [0]
};
}
createItem = () => {
this.setState(prevState => ({numberOfItems: [...prevState.numberOfItems, (this.state.numberOfItems.length - 1)]}));
}
render() {
return(
<div className="NewInvoice">
<button onClick={() => this.props.goBackInvoiceList()} className="goBack">Go back</button>
<h1>New Invoice</h1>
<form>
<p className="FormAreaLabel">Bill From</p>
<div className="BillFrom">
<div className="StreetAddressInput">
<p className="InputLabel">Street Address</p>
<input className="inputFull" type="text" />
</div>
<div className="HalfInput">
<div className="CityInput">
<p className="InputLabel">City</p>
<input className="inputHalf" type="text" />
</div>
<div className="PostCodeInput">
<p className="InputLabel">Post Code</p>
<input className="inputHalf" type="text" />
</div>
</div>
<div className="NewCountryInput">
<p className="InputLabel">Country</p>
<input className="inputFull" type="text" />
</div>
</div>
<div className="BillTo">
<div className="ClientNameInput">
<p className="InputLabel">Client's Name</p>
<input className="inputFull" type="text" />
</div>
<div className="ClientEmailInput">
<p className="InputLabel">Client's Email</p>
<input className="inputFull" type="text" />
</div>
<div className="ClientStreetAddressInput">
<p className="InputLabel">Street Address</p>
<input className="inputFull" type="text" />
</div>
<div className="HalfInput">
<div className="ClientCityInput">
<p className="InputLabel">City</p>
<input className="inputHalf" type="text" />
</div>
<div className="ClientPostCodeInput">
<p className="InputLabel">Post Code</p>
<input className="inputHalf" type="text" />
</div>
</div>
<div className="ClientCountryInput">
<p className="InputLabel">Country</p>
<input className="inputFull" type="text" />
</div>
</div>
<div className="OtherInfo">
<div className="InvoiceDateInput">
<p className="InputLabel">Invoice Date</p>
<input className="inputFull" type="text" />
</div>
<div className="PaymentTermsInput">
<p className="InputLabel">Payment Terms</p>
<input className="inputFull" type="text" />
</div>
<div className="ProjectDescriptionInput">
<p className="InputLabel">Project Description</p>
<input className="inputFull" type="text" />
</div>
</div>
<h3 className="ItemListTitle">Item List</h3>
<div className="ItemList">
{this.state.numberOfItems.map((index) =>
<NewItem key={index} identifier={index} />
)}
<button onClick={() => this.createItem()} className="AddNewItem">+ Add New Item</button>
</div>
</form>
<div className="NewInvoiceEndButtons">
<button className="Discard">Discard</button>
<button className="SaveAsDraft">Save As Draft</button>
<button className="SaveAndSend">Save And Send</button>
</div>
</div>
)
}
}
This is happening because in the h4 line that you specified, you are trying to retrieve a DOM node with the id "QuantityBox" + props.identifier.toString(). Your code is unable to retrieve a DOM element with a matching id, causing document.getElementById(qty) to return null. null doesn't have any properties, so document.getElementById(qty).value is throwing an error specifiying that it cant access property value of null.
Also, if you want to manipulate DOM elements directly, the React way is to use React Refs. You should be able to achieve your desired result with that.
Read more on Refs here: https://reactjs.org/docs/refs-and-the-dom.html
I want to calculate the total(sum) of all the purchases using the "+","-" to add and remove products from the shopping cart.It should display the amount on the left top corner in front of "total:".In front of each product, the total purchase of the single purchase is displayed.
Here a descriptive image
Here the html code:
<body>
<div class="shopping-cart">
<!-- Title -->
<div class="title">
Shopping Bag total :
</div>
<!-- Product #1 -->
<div class="item">
<div class="buttons">
<span class="delete-btn"></span>
<span class="like-btn"></span>
</div>
<div class="image">
<img src="item-1.png" alt="" />
</div>
<div class="description">
<span>Common Projects</span>
<span>Bball High</span>
<span>White</span>
</div>
<div class="quantity">
<button class="plus-btn" type="button" name="button"><img src="plus.svg" alt="" /></button>
<input type="text" value="0" class="input-btn" />
<button class="minus-btn" type="button" name="button"><img src="minus.svg" alt="" /></button>
</div>
<div class="total-price" id="549"><input type="number" value="0" class="result-btn" /></div>
</div>
<!-- Product #2 -->
<div class="item">
<div class="buttons">
<span class="delete-btn"></span>
<span class="like-btn"></span>
</div>
<div class="image">
<img src="item-2.png" alt=""/>
</div>
<div class="description">
<span>Maison Margiela</span>
<span>Future Sneakers</span>
<span>White</span>
</div>
<div class="quantity">
<button class="plus-btn" type="button" name="button"><img src="plus.svg" alt="" /></button>
<input type="text" value="0" class="input-btn" />
<button class="minus-btn" type="button" name="button"><img src="minus.svg" alt="" /></button>
</div>
<div class="total-price" id="270"><input type="number" value="0" class="result-btn" /></div>
</div>
<!-- Product #3 -->
<div class="item">
<div class="buttons">
<span class="delete-btn"></span>
<span class="like-btn"></span>
</div>
<div class="image">
<img src="item-3.png" alt="" />
</div>
<div class="description">
<span>Our Legacy</span>
<span>Brushed Scarf</span>
<span>Brown</span>
</div>
<div class="quantity">
<button class="plus-btn" type="button" name="button"><img src="plus.svg" alt="" /></button>
<input type="text" value="0" class="input-btn" />
<button class="minus-btn" type="button" name="button"><img src="minus.svg" alt="" /></button>
</div>
<div class="total-price" id="349"><input type="number" value="0" class="result-btn" /></div>
</div>
</div>
</body>
Here the JS code:
const items = document.querySelectorAll('.item');
items.forEach(function(item) {
const minusButton = item.querySelector('.minus-btn');
const plusButton = item.querySelector('.plus-btn');
const inputField = item.querySelector('.input-btn');
const resultField = item.querySelector('.result-btn');
minusButton.addEventListener('click', function minusProduct() {
const currentValue = Number(inputField.value);
if (currentValue > 0) {
inputField.value = currentValue - 1;
var x = item.querySelector('.total-price').id;
resultField = item.querySelector('.result-btn').value = x* inputField.value;
} else inputField.value = 0
});
plusButton.addEventListener('click', function plusProduct() {
const currentValue = Number(inputField.value);
if (currentValue < 100) {
inputField.value = currentValue + 1;
var x = item.querySelector('.total-price').id;
resultField = item.querySelector('.result-btn').value = x* inputField.value;
document.querySelector('.title').innerHTML = item.querySelector('.result-btn')[0].value
+item.querySelector('.result-btn')[1].value + item.querySelector('.result-btn')[2].value
} else inputField.value = 100
});
});
There are two thing that you need to do.
1. You need to convert value of total price and total price to number.
2. Set the innneHTML of dev other wise you will get the error. e.g. (
Uncaught TypeError: Assignment to constant variable.
at HTMLButtonElement.minusProduct)
So, in your JS
resultField.innerHTML = item.querySelector('.result-btn').value = Number(x) * Number(inputField.value);
I'm currently using jQuery Validator on a form of mine, when submitting my form it appears that the checked attribute isn't changing on my validator regardless of checked or unchecked.
Here's my HTML:
<div class="col-sm-10 col-sm-offset-1">
<div class="col-sm-6">
<div class="choice" data-toggle="wizard-radio">
<input type="radio" name="platform" value="P1">
<div class="icon">
<img src="{{ asset('images/platform1.png') }}" style="height: 100px;">
</div>
<h6>Platform 1</h6>
</div>
</div>
<div class="col-sm-6">
<div class="choice" data-toggle="wizard-radio">
<input type="radio" name="platform" value="P2">
<div class="icon">
<img src="{{ asset('images/platform2.png') }}" style="height: 100px;">
</div>
<h6>Platform2</h6>
</div>
</div>
<label for="platform" class="error" style="display:none;">Please choose one.</label>
</div>
Here's my JS:
// Code for the Validator
var $validator = $('.wizard-card form').validate({
rules: {
platform: {
required: function () {
var checked = false;
$('input[name="platform"]').each(function() {
if(jQuery(this)[0].hasAttribute('checked')) {
var checked = true;
}
});
console.log(checked);
return checked;
}
}
}
});
I've even tried just using return $('[name="platform"]:checked').length > 0; to no avail.
EDIT
Maybe you are over-complicating the task here...
That simple rule is supposed to work:
$('.wizard-card form').validate({
rules: {
platform: "required"
}
});
.error{
outline:3px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.js"></script>
<div class="wizard-card">
<form>
<div class="col-sm-10 col-sm-offset-1">
<div class="col-sm-6">
<div class="choice" data-toggle="wizard-radio">
<input type="radio" name="platform" value="P1">
<div class="icon">
<img src="https://via.placeholder.com/350x150" style="height: 100px;">
</div>
<h6>Platform 1</h6>
</div>
</div>
<div class="col-sm-6">
<div class="choice" data-toggle="wizard-radio">
<input type="radio" name="platform" value="P2">
<div class="icon">
<img src="https://via.placeholder.com/350x150" style="height: 100px;">
</div>
<h6>Platform2</h6>
</div>
</div>
<label for="platform" class="error" style="display:none;">Please choose one.</label>
</div>
<button id="done">Submit</button>
</form>
</div>
I suggest you read the documentation a bit more closely.
In my code i am using six tabs now i want to know which tab is active .one more thing is that each tab call the same function on clicking and i want to check activation tab(either tab1,tab2 ..) on button click which call other function and in that function i want to check active tab below i explain my problem with code
If i say my problem in one line that want to know active tab on clicking button which call javascript function ,function not on tab clicking*
here i m not putting all code of pages but only require code ,Hope you understand my problems and i provide needed code
Thanks in advance
Add.jsp
This is the page on which i am using tabs
<form action="AddInspServlet" method="Post" enctype="multipart/form-data"> <div>
<div id="slider">
<div class="form-step" >
<div class="row">
<div class="form-left">container Number *</div>
<div class="form-right"><input type="text" id="fname" name="contno" class="form-input" onblur="sending(this.value)"/></div>
<div class="form-error"></div>
</div>
<div class="row">
<div class="form-left">Container type *</div>
<div class="form-right"><input type="text" id="lname" name="conttype" disabled="disabled" class="form-input" /></div>
<div class="form-error"></div>
</div>
<div class="row">
<div class="form-left">Inspection type *</div>
<div class="form-right">
<select id="gender" name="insptype">
<option value="0">Select</option>
<option value="Gate In">Gate In</option>
<option value="Gate Out">Gte Out</option>
</select>
</div>
<div class="form-error"></div>
</div>
<div class="row">
<div class="form-left">Place</div>
<div class="form-right"><input type="text" id="places" name="places" class="form-input" /></div>
<div class="form-error"></div>
</div>
</div>
<div class="form-step" >
<div class="form-left1">
<div class="container1">
<ul class="tabs">
<li>Left</li>
<li>Right</li>
<li>Top</li>
<li>Bottom</li>
<li>Front</li>
<li>Rear</li>
</ul>
<div class="tab_container">
<div id="tab1" class="tab_content">
<div id="hidendiv"></div>
<h2>Left Side</h2>
<div id="leftside">
</div>
<input type="file" name="img1" id="img1" onchange="return ValidateFileUpload('img1')" />
</div>
<div id="tab2" class="tab_content">
<h2>Right Side</h2>
<div id="rightside">
</div>
<input type="file" name="img2" id="img2" onchange="return ValidateFileUpload('img2')" />
</div>
<div id="tab3" class="tab_content">
<h2>Top Side</h2>
<div id="topside">
</div>
<input type="file" name="img3" id="img3" onchange="return ValidateFileUpload('img3')" />
</div>
<div id="tab4" class="tab_content">
<h2>Bottom Side</h2>
<div id="bottomside">
</div>
<input type="file" name="img4" id="img4" onchange="return ValidateFileUpload('img4')" />
</div>
<div id="tab5" class="tab_content">
<h2>Front Side</h2>
<div id="frontside">
</div>
<input type="file" name="img5" id="img5" onchange="return ValidateFileUpload('img5')" />
</div>
<div id="tab6" class="tab_content">
<h2>Rear Side</h2>
<div id="rearside">
</div>
<input type="file" name="img6" id="img6" onchange="return ValidateFileUpload('img6')" />
</div>
</div>
</div>
</div>
<div class="form-right1">
<img src="images/noimg.jpg" height="288px" width="400px" id="blah">
</div>
<div style=" width: 200px; margin-top:225px; margin-left:300px">Remarks: <input type="text" width="100px" name="remark"/></div>
</div>
</div>
</div>
<div class= "ash" style="width:auto; margin-left:35%; float: left;">
<input type="submit" name="btn" id="submit" value="AddInspection" onclick="im()" />
<input type="submit" name="btn" value="Cancel"/>
</div>
</form>
JAVA Script function:
This is the function on which i want to know which tab is active that is defined in above jsp
<script type="text/javascript">
function im()
{
/*alert("calling im function");
var tabname = document.getElementById("tab1");
if(tabname){
alert("tab1 is active");
}else{
alert("tab 1 is not active");
}*/
if($('#img1').val()=="" || $('#img2').val()=="" || $('#img3').val()=="" || $('#img4').val()=="" || $('#img5').val()=="" || $('#img6').val()=="")
{
alert("Please select image");
$('#submit').prop('disabled',true);
}
else
{
$('#submit').prop('disabled',false);
}
}
Try like
$('.tab').click(function(){
var a=$(this).attr('id');
$('#sample').html('Active Tab is'+a);
});
Fiddle
you can assign same class to all tab and bind the click function in document ready, you will get the current object by 'this'.
$('.tab').click(function(){
$(this).val();
});
$('.tab').click(function(){
var x=$(this).prop('id');
$('#lbl').html('Active Tab'+ x);
});
I'm new here but you could add a worthless class to the active tab on click, then on the button click retrieve the id or whatever you want.
jQuery
//edit: added function to add and remove class, replaced text to illustrate
$(function () {
$('.tab_content').click(function () {
$('.tab_content').removeClass('active').text('');
$(this).addClass('active').text('am active');
})
$('#button').click(function () {
$('.tab_content').each(function () {
if ($(this).hasClass('active')) {
alert($(this).attr('id')+" is the active tab");
alert($(this).text()+" is the text");
}
});
});
});
html
<div id='1' class='tab_content'>not</div>
<div id='2' class='tab_content active'>am active</div>
<div id='3' class='tab_content'>not</div>
<div id='4' class='tab_content'>not</div>
<button id='button' style='width:50px; height:50px;'>Click</button>
Here is a working fiddle: http://jsfiddle.net/Lv5VJ/2/
I'm sure there are better ways but hey, I'm trying haha.