Change only one element after clicking other - javascript

I have the following problem:
I would like to change the value of an input field, which is next to an another element, which will be clicked.
HTML:
<div>
<a id="{$sArticle.articleID}" class="minus"><i class="icon-minus-wide"></i></a>
<input class="quantityNum--input quantity{$sArticle.articleID}" name="sQuantity"
type="text" value="{$sArticle.minpurchase}">
<a id="{$sArticle.articleID}" class="plus"><i class="icon-plus-wide"></i></a>
</div>
JS:
$(document).on('click', ".plus", function (event) {
let currentTarget = event.currentTarget;
let idOfClickedElement = $(currentTarget).attr('id');
let currentQuantity = Number($('.quantity' + idOfClickedElement).val());
$(this).parent().find(".quantity" + idOfClickedElement).val(currentQuantity + 1)
});
There are other input fields which are the same like in the example. Those value changes also, but I want only one.

As each input with +/- is inside a div wrapper, you can use
$(this).closest("div").find(".quantityNum--input")
to get the related input.
There's no need for the numeric IDs when using relative DOM traversal.
Combining the + and - into a single event gives:
$(document).on('click', ".minus,.plus", function() {
var delta = $(this).is(".plus") ? 1 : -1;
$(this).closest("div").find(".quantityNum--input").val((i, val) => {
console.log(val);
return (val * 1) + delta;
});
});
.minus,
.plus {
cursor: pointer
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<a class="minus">[-]<i class="icon-minus-wide"></i></a>
<input class="quantityNum--input" name="sQuantity" type="text" value="100">
<a class="plus">[+]<i class="icon-plus-wide"></i></a>
</div>
<div>
<a class="minus">[-]<i class="icon-minus-wide"></i></a>
<input class="quantityNum--input" name="sQuantity" type="text" value="500">
<a class="plus">[+]<i class="icon-plus-wide"></i></a>
</div>

I thik you are looking for .next and .prev.
note: I like sharing information usingdata-attributes so I've used that. you can use anything else id/class to differentiate. that's upto you
Just created a demo script for you
$('.number-action-button').on('click', function(){
const direction = $(this).data('direction');
if(direction === 'decrement'){
const $input = $(this).next('input[type="number"]');
$input.val($input.val() - 1);
}
if(direction === 'increment'){
const $input = $(this).prev('input[type="number"]');
$input.val(parseInt($input.val()) + 1);
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="number-action-button" data-direction="decrement">-</button>
<input type="number" value="0" />
<button class="number-action-button" data-direction="increment" >+</button>

simple solution: bundle the 3 elemts into 1 container, so your parent selector can easily catch the input, the way you already do it.
<div>
<a id="{$sArticle.articleID}" class="minus"><i class="icon-minus-wide"></i></a>
<input class="quantityNum--input quantity{$sArticle.articleID}" name="sQuantity"
type="text" value="{$sArticle.minpurchase}">
<a id="{$sArticle.articleID}" class="plus"><i class="icon-plus-wide"></i></a>
</div>
if you cant(or dont want) change the html use $(this).next() (or $(this).prev() for the plus button) in order to fint the input.
btw: maybe you'll try that funktion (havn't tested it, but at least it should give you an idea how to)
$(document).on('click', ".plus,.minus", function (event) {
let input_quantity=false;
if($(this).hasClass('plus'){
input_quantity=$(this).prev();
input_quantity.val(parseInt(input_quantity.val())+1);
}else{
input_quantity=$(this).next();
input_quantity.val(parseInt(input_quantity.val())-1);
}
});

Related

how to display the array of values for the single field using jquery?

Here I need to get all the values entered in the input field. But it echoes only the first value.
ie. When I press the + and give some values, I need to get that value too.
$(document).ready(function() {
$(document).on("click", ".add", function() {
var clone = '<div class="add1"><input type="text" name="selprice" /><input type = "submit" value = "+" class = "add" ><input type = "submit" value = "-" class = "remove" ></div>';
$(this).closest('.add1').after(clone);
});
$(document).on("click", ".remove", function() {
$(this).parent(".add1").remove();
});
});
$('#package').change(function() {
var arr = [];
$("input.packageclass").each(function() {
arr.push($(this).val());
alert(arr);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div class="add1">
<h6>Sales Package </h6>
<div>
<input type="text" name="package" placeholder="Ex:34" id="package" class="packageclass">
<input type="submit" value="+" class="add"></div>
</div>
$('.package').change(function() {
You are using an ID in your input type="text". IDs are only used once. If you want to add the listener to all of your textfields use classes.
In addition to that the .change(function() is only once called, when the dom is ready. That will be a problem too. So the change listener is not added to the generated textfields. Maybe you use something like...
$('.package').on('change', 'input', function() {
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div class="add1">
<h6>Sales Package </h6>
<div>
<input type="text" name="package" placeholder="Ex:34" id="package" class="packageclass">
<input type="submit" value="+" class="add">
</div>
</div>
<script type="text/javascript">
var addInput = function(e) {
var arr = [];
$("input.packageclass").each(function() {
arr.push($(this).val());
});
alert(arr);
};
$(document).ready(function() {
$(document).on("click", ".add", function() {
var clone = '<div class="add1"><input class="packageclass" type="text" name="selprice" /><input type = "submit" value = "+" class = "add" ><input type = "submit" value = "-" class = "remove" ></div>';
$(this).closest('.add1').after(clone);
$('.packageclass').unbind().bind('change', addInput);
});
$(document).on("click", ".remove", function() {
$(this).parent(".add1").remove();
});
});
$('.packageclass').unbind().bind('change', addInput);
</script>
Just using loop you can get the particular value from loop.
for (var i = arr.length - 1; i >= 0; i--) {
arr[i];
//work with arr[]
}
I have used event delegation to capture the events and take appropriate action.
In this, you can add a event listener to your parent element i.e., click to the .body in my case. When I click on the .add button, the event propagates and .body click handler gets invoked. By checking for event.target we can find out the origin of event and add or remove the divs.
Similary we can listen for the change event of the input boxes and take appropriate actions.
$('#body').click(function(e) {
if(e.target.className === 'add') {
$('#body').append(`
<div class="add1">
<input type="text" name="package" placeholder="Ex:34" id="package" class="packageclass">
<button class="add">+</button>
<button class="remove">-</button>
</div>
`);
}
if(e.target.className === 'remove') {
$(e.target).parent().empty();
}
});
$('#body').change(function(e) {
console.log(e.target.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div id="body">
<h6>Sales Package </h6>
<div class="add1">
<input type="text" name="package" placeholder="Ex:34" id="package" class="packageclass">
<button class="add">+</button>
</div>
</div>
Just add class="packageclass" to the input when creating your clone variable.
https://jsfiddle.net/289xvmu7/
var clone = '<div class="add1"><input type="text" name="selprice" class="packageclass"/> <input type = "submit" value = "+" class = "add" ><input type = "submit" value = "-" class = "remove" ></div>';

Input field validated only for first input field and not able to remove input field

I had created Ul which add the student input field with value and user can remove the field as well,Initially I am comparing student field value with each input field which are created to avoid duplication but it works only for first input field value not for others I used loop as well but its not working and not able to remove one input field at a time.
Here is my fiddle code
$('#addBtn').click(function () {
var studentArray = $(".students").text();
var i=" " ;
console.log(studentArray);
var studentSplitResult = studentArray.split('Remove');
console.log(studentSplitResult);
for (var i = 0; i < studentSplitResult.length; i++) {
if ($("#selectStd").val() !== $(".students").val()) {
$(".stdList").show();
var input_value = $('#selectStd').val();
$('ul').append('<input class="students" value="' + input_value + '">Remove</input>');
console.log($(".students").val());
// console.log(studentSplitResult[i]);
};
return false;
}
});
//prevent default action
$(document).on('click', 'a', function (e) {
e.preventDefault();
$(this).parent().remove();
});
You can simplify your code like below.
Just check any text input has the new value before adding using filter. It will also handle case insensitivity (remove if required).
Also while removing consider the removing the text input only.
Added e.preventDefault() to restrict the form posting. change or remove it as per requirement.
$('#addBtn').click(function(e) {
e.preventDefault();
var input_value = $("#selectStd").val();
var isValid = $('input.students').filter(function() {
return this.value.toLowerCase() == input_value.toLowerCase();
}).length <= 0;
if (isValid) {
$('ul').append('<input class="students" value="' + input_value + '">Remove</input>');
} else {
alert('Duplicate');
}
});
//prevent default action
$(document).on('click', 'a.deleteStd', function(e) {
e.preventDefault();
$(this).prev('.students').remove();
$(this).remove();
});
<body>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<div class="panel panel-body" style=" width:422px;border: 1px solid #00A4CC;">
<div id="errorLabel"></div>
<div id="parentType">
<form id="parentForm" name="parentForm">
<table style="margin-left: 8px;">
<tr>
<th>Select Student</th>
<td><input class="form-control" id="selectStd" placeholder="Please select students"></td>
<td><button id="addBtn" class="btn btn-default" style="margin-left: 17px;">Add</button></td>
</tr>
</table>
<ul class="stdList">
<label>Selected Students:</label><br>
<br>
</ul>
<table>
</table>
</form>
</div>
</div>
</div>
</body>
I have encountered two issues: input validation itself (your question) and the removal of the element when you click on the anchor element.
For input validation, I have rewritten it a bit. What I did is
1. Obtain new student value
2. Check if not empty by if(newStudent). If it's empty, nothing happens
3. obtain other inputs
4. match the new input against the values inside other inputs
4a. if match, don't add it.
4b. if no match, add it
For removing the element, You need to revise your HTML. It's not so correct. I have wrapped it around with a <section> element to have a save removal and corrected the HTML use.
A side note, you may also reconsider this
$(document).on('click', 'a', function(e) {
e.preventDefault();
$(this).parent().remove();
});
If your HTML page has multiple anchor (<a>) elements, this function is used too on another anchor elements. If you click on these, it will remove these from the page upon click. If you don't want it, please revise the above function.
$('#addBtn').click(function(e) {
// obtain new student value
var newStudent = $('#selectStd').val();
// check if it is not empty
if (newStudent) {
// obtain other names and check if there is no match
var studentArray = $(".students");
var hasMatch = false;
studentArray.each(function(i, el) {
if (el.value === newStudent) {
hasMatch = true;
return; // stopping loop
}
});
// if there is no match, add student
if (!hasMatch) {
$('ul.stdList').append('<section><input class="students" value="' + newStudent + '" />Remove</section>');
}
}
return false;
});
//prevent default action
$(document).on('click', 'a', function(e) {
e.preventDefault();
$(this).parent().remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel panel-body" style=" width:422px;border: 1px solid #00A4CC;">
<div id="errorLabel"></div>
<div id="parentType">
<form id="parentForm" name="parentForm">
<table style="margin-left: 8px;">
<tr>
<th>Select Student</th>
<td>
<input class="form-control" id="selectStd" placeholder="Please select students">
</td>
<td>
<button id="addBtn" class="btn btn-default" style="margin-left: 17px;">Add</button>
</td>
</tr>
</table>
<ul class="stdList">
<label>Selected Students:</label>
<br>
<br>
</ul>
</form>
</div>
</div>
When adding you try this:
$('ul').append('<input class="students" value="' + input_value + '">Remove</input>');
Unfortunately this will not result in what you expect. The anchor will be adding by your browser next to the input not nested. Like this:
<input class="students" value="thevalue" />
<a href class="deleteStd">Remove</a>
So if you do this afterwards for removing $(this).parent().remove(); you will remove the entire container.
What you need to do is this:
$('ul').append('<div><input class="students" value="' + input_value + '" />Remove</div>');
This will work. I have updated your fiddle: https://jsfiddle.net/Lojdfyhn/1/
So based on your requirements, try this below code:
Student names can't be duplicate
And on removing, all names shouldn't removed.
While adding, code checks if the student name exists. If yes, it throws an error/alert.
$('#addBtn').click(function() {
var valueToCheck = $("#selectStd").val();
var flag = true;
$(".students").each(function() {
if ($(this).val() === valueToCheck) {
flag = false;
}
});
if (flag) {
$('ul').append('<span class="addedStudent"><input class="students" value="' + valueToCheck + '" />Remove</span>');
} else {
alert(valueToCheck + " already exists.");
}
return false;
});
//prevent default action
$(document).on('click', 'a.deleteStd', function(e) {
e.preventDefault();
$(this).parents(".addedStudent:first").remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel panel-body" style=" width:422px;border: 1px solid #00A4CC;">
<div id="errorLabel"></div>
<div id="parentType">
<form id="parentForm" name="parentForm">
<table style="margin-left: 8px;">
<tr>
<th>Select Student</th>
<td><input class="form-control" id="selectStd" placeholder="Please select students"></td>
<td><button id="addBtn" class="btn btn-default" style="margin-left: 17px;">Add</button></td>
</tr>
</table>
<ul class="stdList">
<label>Selected Students:</label><br>
<br>
</ul>
<table>
</table>
</form>
</div>
</div>
You are trying to delete the parent element of anchor tag.
Just update your code like this
$('ul').append('<div><input class="students" value="' + input_value + '">Remove</input></div>');
then clicking on anchor will delete the parent of anchor element.
Hello first of all you need to get a good understanding of the DOM traversing, which can really help you to organise the students that you are adding to the list, and removing.
Here a simple solution can be implemented as follows.
First encapsulate all the students in a div tag with 'students' class name, and in that div, place the student text field with 'stdname' class and the anchor tag to help in removing the student details.
Now when traverse through all the students with 'stdname' class and check if there is a duplicate value.
Here is the code please check out.
and check on jsfiddle too.http://jsfiddle.net/naveen_namani/842bf5ke/1/
$('#addBtn').click(function () {
var student_list=document.querySelectorAll(".students .stdname");
var selectStd=document.getElementById("selectStd");
var duplicate=false;
for(var i=0;i<student_list.length;i++) {
if(student_list[i].value==selectStd.value) duplicate=true;
}
if(duplicate==false) {
$('ul').append('<div class="students"><input value="'+selectStd.value+'" class="stdname"/>Remove');
}
return false;
});
$(document).on('click', 'a', function (e) {
e.preventDefault();
$(this).parent().remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel panel-body" style="width:422px;border:1px solid #00A4CC;">
<div id="errorLabel"></div>
<div id="parentType" >
<form id="parentForm" name="parentForm">
<table style="margin-left: 8px;">
<tr>
<th>Select Student</th>
<td>
<input class="form-control" id="selectStd" placeholder="Please select students">
</td>
<td>
<button id="addBtn" class="btn btn-default" style="margin-left: 17px;" >Add</button>
</td>
</tr>
</table>
<ul class="stdList">
<label>Selected Students:</label>
<br><br>
</ul>
<table ></table>
</form>
</div>
</div>

Calculating TOTAL in added input fields

I have this small problem. I have been checking out the net to find an answer, but it is mostly for input fields which aren't generated / added.
<script>
$(document).ready(function(){
/* --- ADD FIELD --- */
$('.TotalMultiField').each(function() {
var $wrapper = $('.multiFields', this);
$(".addField", $(this)).click(function(e) {
$('.multiField:first-child', $wrapper).clone(true).appendTo($wrapper).find('input').val('').focus();
});
/* --- REMOVE FIELD --- */
$('.multiField .removeField', $wrapper).click(function() {
if ($('.multiField', $wrapper).length > 1)
$(this).parent('.multiField').remove();
});
});
</script>
Above is the Jquery script to add and remove fields. And below is the HTML code. As you see, in the "insert a number" field, the total should appear in the span id="added".
<form role="form" action=""" method="">
<div class="TotalMultiField">
<div class="multiFields">
<div class="multiField">
<input type="date">
<input type="number" class="number" placeholder="Insert a number">
<button type="button" class="removeField">Remove</button>
</div>
</div>
<button type="button" class="addField">Add field</button>
</div>
Total:<span id="added"></span>
</form>
Just noticed you updated that you do indeed want a sum, here is a fiddle with the total calculated on blur and when you remove a row, bind additional events as required (some tidy up is required, but this should get you started):
http://jsfiddle.net/1ggaco1d/4/
The below code does the totaling:
function total() {
var total = 0;
$(".number").each(function (idx, el) {
var value = $(el).val();
if (value !== "") {
total = total + parseFloat($(el).val());
}
});
$("#added").text(total);
}
Please check the below fiddle
https://jsfiddle.net/srsu4rne/
You should be able to just count the classes in the div
var multiField = $('.multiField').length
$('#added').html(multiField);

How do I add up values of buttons in jquery

I'm trying to sum up values of buttons if the buttons are clicked on. For example, there is "Button1". If this button is clicked, it should add its value to a sum which will be displayed at the bottom of the page. If "Button1" is clicked a second time it should substract its value from the sum.
Here is my attempt to do this but it's not doing anything at all:
var value_Buttons = 0;
var total = 0;
$("button[name=Button1],[name=Button2],[name=Button3],[name=Button4],[name=Button5],[name=Button6]").click(function() {
if($(this).hasClass('active') == false) {
value_Buttons += parseInt($(this).val());
} else if($(this).hasClass('active') == true) {
value_Buttons -= parseInt($(this).val());
}
total += value_Buttons;
alert(total);
});
total = value_Buttons + value_Optional_Button;
$("input[name=value_sum]").val(total);
Additionally, here is the code for an examplary button (Like "Button1"):
<div class="form-group col-md-2">
<button type="button" class="form-control btn btn-primary" name="Button1" value="300" title="300 €" data-toggle="button" aria-pressed="false" autocomplete="off">Button 1</button>
</div>
There will be more buttons, but they will only differ in their name and value.
Also, the box which will display the sum of the button-values currently looks like this:
<div>
<label class="control-label">Sum</label>
<div class="input-group">
<input class="form-control" name="value_sum" style="text-align:right" id="costs" value="" type="text" readonly>
<span class="input-group-addon">€</span>
</div>
</div>
I've searched all over Stackoverflow, as well as via Google, etc. yet I can't find anything or anyone with a similar problem
Blocking JS logic error is here :
$("input[name=value_sum]").val(total);
this line should be in the above code block. Added corrections for substraction :
var total = 0;
$("button[name]").on("click", function() {
if(!$(this).hasClass('active')) {
total += Number($(this).val());
$(this).addClass('active').html("remove " + $(this).attr("title"));
} else {
total -= Number($(this).val());
$(this).removeClass('active').html("add " + $(this).attr("title"));
}
$("input[name=value_sum]").val(total);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group col-md-2">
<button type="button" class="form-control btn btn-primary" name="Button300" value="300" title="300 €" data-toggle="button" aria-pressed="false" autocomplete="off">add 300 €</button>
<button type="button" class="form-control btn btn-primary" name="Button600" value="600" title="600 €" data-toggle="button" aria-pressed="false" autocomplete="off">add 600 €</button>
</div>
<div>
<label class="control-label">Sum</label>
<div class="input-group">
<input class="form-control" name="value_sum" style="text-align:right" id="costs" value="0" type="text" readonly>
<span class="input-group-addon">€</span>
</div>
</div>
Lines 14 and 15 need to be placed within the click event of the button to update the value_sum input on every click. Also your selection for the value attribute it a little bit off. The way to return the value attribute of a button using jQuery is:
$(this).attr('value');
So after these two points, stripping your code of the if and else check, and also selecting the buttons with a cleaner method, you should have something like this:
var total = 0;
$("button[name=Button1], button[name=Button2], button[name=Button3], button[name=Button4], button[name=Button5], button[name=Button6]").click(function() {
total += $(this).attr('value');
$("input[name=value_sum]").val(total);
});
To display the total, that is 0, in the input element on page load, you could use:
<input class="form-control" name="value_sum" style="text-align:right" id="costs" value="0" type="text" readonly>
start off by create a listener for a class that will be applied to all of your buttons.
$(.btn).click(function() {
//get value
var value = parseint($(this).attr("value"));
//check if already clicked
if($(this).hasClass('active') {
//set value of total
total = total - value;
//remove class active
$(this).removeClass('active');
}else {
//set value of total
total = total + value;
//addclass active
$(this).addClass('active');
}
)};
Is this what you need?
Working Demo
Here have added a classname 'add' for all buttons , on click its toggle class add, sub in you case you using active,inactive class
var total = 0;
$("button[name=button1],[name=button2],[name=button3]").on('click', function () {
var self = $(this);
var gValue = Number(self.val());
if (self.hasClass("add")) {
total += gValue;
self.removeClass("add").addClass("sub");
} else {
total -= gValue;
self.removeClass("sub").addClass("add");
}
$("#costs").val(total);
});
Check this fiddle.
Add as many buttons as you like, the only thing is that you'll have to add a data-value to them to figure out how much to add or substract. I would also do the search for buttons using a class instead of "button" but that's up to you.
var buttons = {};
$("button").each(function (index, item) {
buttons[index] = 0;
$(item).click(function () {
var value = +($(item).data("value")),
val = +($("#costs").val());
val += (!buttons[index]) ? value : -value;
buttons[index] = (!buttons[index]) ? 1: 0;
$("#costs").val(val);
});
});
Hope it helps.

Jquery: How to reorder DIVs after removing a single Div?

I am working on an application in which contains a few DIVs having IDs like a1,a2,a3 etc.
There is option of navigation DIVs by hitting next and previous button which brings one Div on screen at a time. strong text There are two more actions: Add and Remove. Add adds a Div with ID greated than last ID, for instance if last DIV id was a3 then Add brings a4.
The real issue is removing current DIV. If the user is on Div a2 and hits Remove option then it deletes the current Div by using .remove() method of jQuery
Now navigation breaks because it is sequential. It tries to find Div a2 but does not find. What I think that Ids of all remaining DIVs should be renamed. Since there is no a2 so a3 should become a2 and so on. How can I do that? Code doing different tasks is given below:
function removeQuestion()
{
$("#_a"+answerIndex).remove();
if(answerIndex > 1)
{
if ($("#_a"+(++answerIndex)).length > 0)
{
$("#_a"+answerIndex).appendTo("#answerPanel");
}
else if($("#_a"+(--answerIndex)).length)
{
$("#_a"+answerIndex).appendTo("#answerPanel");
}
totalOptions--;
}
}
function addQuestion()
{
var newId = 0;
totalOptions++;
var d = 1;
newId = totalOptions;
var _elemnew = '_a'+newId;
$("#_a"+d).clone().attr('id', '_a'+(newId) ).appendTo("#answers_cache");
var h = '<input onclick="openNote()" id="_note'+newId+'" type="button" value=" xx" />';
$("#"+_elemnew+" .explain").html(h)
$("#"+_elemnew+" ._baab").attr("id","_baab"+newId);
$("#"+_elemnew+" ._fx").attr("id","_fasal"+newId);
$("#"+_elemnew+" .topic_x").attr("id","_t"+newId);
$("#"+_elemnew+" .topic_x").attr("name","_t"+newId);
$("#"+_elemnew+" .answerbox").attr("id","_ans"+newId);
$("#"+_elemnew+" .block").attr("onclick","openFullScreen('_ans"+newId+"')");
$('.tree').click( function()
{
toggleTree();
}
);
$('.popclose').click( function()
{
unloadPopupBox();
}
);
}
function next()
{
console.log("Next ->");
if(answerIndex < totalOptions)
{
answerIndex++;
console.log(answerIndex);
setInitialAnswerPanel();
}
}
function previous()
{
console.log("Next <-");
if(answerIndex > 1)
{
answerIndex--;
console.log(answerIndex);
setInitialAnswerPanel();
}
}
Html of Composite DIV is given below:
<div class="answers" id="_a1" index="1">
<input placeholder="dd" id="_t1" type="text" name="_t1" class="urduinput topic_masla" value="" />
<img class="tree" onclick="" src="tree.png" border="0" />
<label class="redlabel">
xx :
</label>
<label id="_baab1" class="baabfasal _baab">
</label>
<label class="redlabel">
xx :
</label>
<label id="_fasal1" class="baabfasal _fasal">
</label>
<a title=" ddd" class="block" href="#" onclick="openFullScreen('_ans1')">
<img src="fullscreen.png" border="0" />
</a>
<textarea id="_ans1" class="answerbox" cols="40" rows="15"></textarea>
<span class="explain">
<input onclick="openNote()" id="_note1" type="button" value=" xx" />
</span>
<span style="float:left;padding-top:5%">
plus | <a onclick="removeQuestion()" href="#">minus</a>
</span>
</div>
Why don't you keep currently opened page instead of the index and search for previous and next pages using prev() and next() jQuery tree traversal methods?
Select all div elements containing questions, preferable with a css class selector, use the each method, and assign new ids to them:
$('.questionDiv').each(function(index) { $(this).attr('id', 'a' + (index + 1)); })
That should be enough.
var originalSet = $('.answers');
var container = originalSet.up() ;
var byId = function(a, b){
return $(a).attr('id') > $(b).attr('id') ? 1 : -1;
}
originalSet
.order(byId)
.each(function rearrangeIds(position){
$(this).attr({
'index': poition,
'id': '_a'+position
});
}).appendTo(container)

Categories