Sortable not changing ids - javascript

I want to be able, when I drag and drop, to replace all ids by the other.
For example in this code :
<div class="container">
<div class="row" id="row_0">
<div class="col-md-12">
<form id="form_0" onsubmit="return false;">
<select class="select2" name="test1" id="test1_0">
<option value="o_test">o_test1_1</option>
<option value="o_test">o_test1_2</option>
<option value="o_test">o_test1_3</option>
</select>
<select class="select2" name="test2" id="test2_0">
<option value="o_test">o_test2_1</option>
<option value="o_test">o_test2_2</option>
<option value="o_test">o_test2_3</option>
</select>
<button onclick="addRow()">clone</button>
</form>
</div>
</div>
<div class="row" id="row_1">
<div class="col-md-12">
<form id="form_1" onsubmit="return false;">
<select class="select2" name="test1" id="test1_1">
<option value="o_test">o_test1_1</option>
<option value="o_test">o_test1_2</option>
<option value="o_test">o_test1_3</option>
</select>
<select class="select2" name="test2" id="test2_1">
<option value="o_test">o_test2_1</option>
<option value="o_test">o_test2_2</option>
<option value="o_test">o_test2_3</option>
</select>
<button onclick="addRow()">clone</button>
</form>
</div>
</div>
</div>
I want to be able to change when I drag and drop all id="form_0" <-> id="form_1",id="row_0" <-> id="row_1", id="test1_0" <-> id="test1_1" .. etc, this is just an example, there are more.
I know that we can use the stop option like so :
$('.container').sortable({
stop: function(event, ui) {
var moved = ui.item,
replaced = ui.item.prev();
if (replaced.length == 0) {
replaced = ui.item.next();
}
var moved_num = parseInt(moved.attr("id").match(/\d+/g), 10) + 1;
var replaced_num = parseInt(replaced.attr("id").match(/\d+/g), 10) + 1;
moved.find('[id]').each(function() {
var $this = $(this),
split = $this.prop('id').split('_')[0];
$this.prop('id', $this.prop('id').split('_')[0] + '_' + replaced_num);
});
replaced.find('[id]').each(function() {
var $this = $(this),
split = $this.prop('id').split('_')[0];
$this.prop('id', $this.prop('id').split('_')[0] + '_' + moved_num);
});
}
});
The idea here in the code above, is to get the id number of the one moved and replaced, and for each id, replace in each one of them the number of the other.
But it doesn't do what I'm trying to do. Any idea why?
Fiddle : https://jsfiddle.net/763opz0c/

My suggestion is loop through all items and use their index within the container to update all id's
$('.container').sortable({
stop: function(event, ui) {
var $items = $(ui.item).parent().children()
$items.each(function(index){
$(this).find('[id]').add(this).attr('id', function(){
return this.id.split('_')[0] +'_' + index
});
});
}
});
Fiddle demo

Related

loop my select options using input="number"?

Here is my Fiddle
<input type="number" id="test" onkeydown="javascript:return event.keyCode==69? false:true" name="form_select" class="text" onchange="showDiv()">
<select id="hidden_div1" style="display:none;" name="form_select">
<option value="0">No</option>
<option value ="1">Yes</option>
</select>
<div id="allcontent1"></div>
<script>
function showDiv(){
allselect="";
getSelectValue = parseInt(document.getElementById("test").value);
if(getSelectValue > 0){
for (let i=0;i<getSelectValue;i++){
allselect+=document.getElementById("hidden_div1").style.display="block";}
}else{
document.getElementById("hidden_div1").style.display="none";
}
document.getElementById("allcontent1").innerHtml = allselect;
}
</script>
I wanted to iterate my select elements, using javascript only

Get the value of select class options

I'm working on a test/quiz and I can't solve a problem.
I like to grab the selected value from a option and print it to the result p.
<div class="add">
<div class="add__container">
<select class="add__type">
<option value="0" id="a01" selected>No</option>
<option value="1" id="a02">Ocassionally</option>
<option value="2" id="a03">Yes</option>
</select>
</div>
</div>
<button class="btn" onclick="myValue()">Results</button>
<p id="result">... </p>
And here is my Javascript code where I'm stucked:
function myValue(){
var e = document.getElementById("s01");
var value = e.options[e.selectedIndex].value;
var text = e.options[e.selectedIndex].text;
document.getElementById('result').innerHTML = e;
};
try this code. I think this code work like you requirement.
function myValue(){
var select = document.getElementsByClassName("add__type")[0].value;
document.getElementById('result').innerHTML = select;
};
<div class="add">
<div class="add__container">
<select class="add__type">
<option value="0" id="a01" selected>No</option>
<option value="1" id="a02">Ocassionally</option>
<option value="2" id="a03">Yes</option>
</select>
</div>
</div>
<button class="btn" onclick="myValue()">Results</button>
<p id="result">... </p>
something more..
I think you want to put the actual text of the selected option in the innerHtml instead of the option DOM element:
document.getElementById('result').innerHTML = text;
Maybe you want this? I added the id "s01" on select.
<div class="add">
<div class="add__container">
<select id="s01" class="add__type">
<option value="0" id="a01" selected>No</option>
<option value="1" id="a02">Ocassionally</option>
<option value="2" id="a03">Yes</option>
</select>
</div>
</div>
<button class="btn" onclick="myValue()">Results</button>
<p id="result">... </p>
<script>
function myValue() {
var e = document.getElementById("s01");
var value = e.options[e.selectedIndex].value;
var text = e.options[e.selectedIndex].text;
document.getElementById('result').innerHTML = text;
};
</script>
// Unimportant stuff
const $ = document;
$.get = $.getElementById;
$.get('theOptions').addEventListener('change', function(event) {
// Get the value from the select-element
$.get('out').innerHTML = 'You selected ' + event.target.value; // Or $.get('theOptions').value
});
<select id="theOptions">
<option value="o1">Option 1</option>
<option value="o2">Option 2</option>
<option value="o3">Option 3</option>
</select>
<span id="out">Nothing selected</span>

How to condense hardcoded jQuery code to smaller generic code?

I have a code that works perfectly fine because it is hardcoded but extremely large. I would like to simplify this code to make it general and of course smaller. Does anybody know how to do this? Since it is so large I will shrink it down for this question.
var theform1 = $('#form1').find('.state option');
var stateForm1 = Object.keys(localStorage).filter(key => key.endsWith('-state1'));
var stateChoice1 = JSON.parse(localStorage.getItem(stateForm1));
var theform2 = $('#form2').find('.state option');
var stateForm2 = Object.keys(localStorage).filter(key => key.endsWith('-state2'));
var stateChoice2 = JSON.parse(localStorage.getItem(stateForm2));
var theform3 = $('#form3').find('.state option');
var stateForm3 = Object.keys(localStorage).filter(key => key.endsWith('-state3'));
var stateChoice3 = JSON.parse(localStorage.getItem(stateForm3));
if (localStorage.getItem(stateForm1)) {
$(theform1).empty();
$(theform1).val(stateChoice1).append(`<option value="${stateChoice1}">${stateChoice1}</option>`).trigger('window.load');
};
if (localStorage.getItem(stateForm2)) {
$(theform2).empty();
$(theform2).val(stateChoice2).append(`<option value="${stateChoice2}">${stateChoice2}</option>`).trigger('window.load');
};
if (localStorage.getItem(stateForm3)) {
$(theform3).empty();
$(theform3).val(stateChoice3).append(`<option value="${stateChoice3}">${stateChoice3}</option>`).trigger('window.load');
};
The HTML markup is as follows:
<form id="form1" autocomplete="off">
<select id="country1" class="country" name="country">
<?php include("countryAjaxData.php"); ?>
</select>
<select id="state1" class="state" name="state">
<option value="" selected="selected">Select state</option>
</select>
<select id="city1" class="city" name="city">
<option value="" selected="selected">Select city</option>
</select>
</form>
<form id="form2" autocomplete="off">
<select id="country2" class="country" name="country">
<?php include("countryAjaxData.php"); ?>
</select>
<select id="state2" class="state" name="state">
<option value="" selected="selected">Select state</option>
</select>
<select id="city2" class="city" name="city">
<option value="" selected="selected">Select city</option>
</select>
</form>
<form id="form3" autocomplete="off">
<select id="country3" class="country" name="country">
<?php include("countryAjaxData.php"); ?>
</select>
<select id="state3" class="state" name="state">
<option value="" selected="selected">Select state</option>
</select>
<select id="city3" class="city" name="city">
<option value="" selected="selected">Select city</option>
</select>
</form>
Maybe you're looking for this compressed version:
$('#form1,#form2,#form3').each(function () {
var index = this.id.substring(this.id.length - 1, this.id.length);
var stateForm = Object.keys(localStorage).filter(key => key.endsWith('-state' + index));
var stateChoice = JSON.parse(localStorage.getItem(stateForm));
if (localStorage.getItem(stateForm)) {
var theform = $(this).find('.state option').empty();
theform.val(stateChoice)
.append(`<option value="${stateChoice}">${stateChoice}</option>`)
.trigger('window.load');
}
});
If you have more than 10 forms with the index increasing from 1 to 99 or 999... You can edit the way to name your form id to: form01 form02 form03 or form001 form002 form003...
Then, because all of the id names start with form, you can update the selectors like this:
Changing $('#form1,#form2,#form3') to $('[id^="form"]'). That selector means: selecting some element(s) which contains the id starts with form.
Lastly, if your form id following by 2 digits (form01), you update the line to get the index to:
var index = this.id.substring(this.id.length - 2, this.id.length);
You can do the same way for the ids following by 3 digits (form001):
var index = this.id.substring(this.id.length - 3, this.id.length);
Loop over all the select.state and get the number from the parent form.
Something like:
$('select.state').each(function() {
const $sel = $(this),
formNum = $sel.closest('form').attr('id').replace('form', ''),
stateForm = Object.keys(localStorage).find(key => key.endsWith(`-state${formNum }`)),
stateChoice = localStorage.getItem(stateForm);
if (stateChoice) {
$sel.append(new Option(stateChoice. stateChoice))
.val(stateChoice)
.trigger('window.load');
}
})
Note I changed filter() to find() for the keys since filter returns an array

Find total of dropdown selection values with jquery

I'm creating a form that allows a user to select an amount of services, and then a total is displayed. I have it working to where I can keep the running total of one drop down menu service, but then I can't figure out how to add additional services from other drop down menus. For example, I need it so that if someone selects '3' from one drop down menu, it will times that value by 10 (I have that part done), but then also be able to select a '4' from the next dropdown menu and times that by a value, and then display a total.
Fiddle: https://jsfiddle.net/7jrch7w6/
I'm very new to JavaScript and JQuery, so feel free to give suggestions if you see a better way or if my code is garbage. Thanks!
Here's my code:
<form>
<div id="carpet-services">
<div class="form-group">
<!--how many bedrooms-->
<label class="control-label" for="carpet_cleaning">Bedrooms</label>
<select class="form-control" id="carpet_cleaning">
<option value="0-bedroom">0</option>
<option value="1-bedroom">1</option>
<option value="2-bedroom">2</option>
</select>
<label class="hide" for="0-bedroom">0</label>
<label class="hide" for="1-bedroom">1</label>
<label class="hide" for="2-bedroom">2</label>
<!--how many dining rooms-->
<label class="control-label" for="dining_rooms">Dining Rooms</label>
<select class="form-control" id="dining_rooms">
<option value="0-diningRoom">0</option>
<option value="1-diningRoom">1</option>
<option value="2-diningRoom">2</option>
</select>
<label class="hide" for="0-diningRoom">0</label>
<label class="hide" for="1-diningRoom">1</label>
<label class="hide" for="2-diningRoom">2</label>
</div>
</div>
<h4>Total Price</h4>
<p id="output1"></p>
JS
$("#carpet_cleaning").change(function () {
var bedrooms = $("#carpet_cleaning").val();
var diningRooms = $("#dining_rooms").val();
var bedroomPrice = '';
var diningRoomPrice = '';
if (carpet_cleaning){
var bedroomsLabel = $("label[for="+bedrooms+"]").text();
bedroomPrice = 'Your price quote is: ' + bedroomsLabel * 10;
}
$("#output1").text(bedroomPrice).fadeIn();
});
One line of CSS:
label.hide {display: none;}
First of all, there's no need to use labels for every drop down option, that's what value attribute is for:
<form>
<div id="carpet-services">
<div class="form-group">
<!--how many bedrooms-->
<label class="control-label" for="carpet_cleaning">Bedrooms</label>
<select class="form-control" id="carpet_cleaning">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<!--how many dining rooms-->
<label class="control-label" for="dining_rooms">Dining Rooms</label>
<select class="form-control" id="dining_rooms">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
</div>
<h4>Total Price</h4>
<p id="output1"></p>
</form>
Calculation can now be simplified and properly hooked up to change event of both drop downs:
$("#carpet_cleaning,#dining_rooms").change(function () {
var bedrooms = $("#carpet_cleaning").val();
var diningRooms = $("#dining_rooms").val();
var total = bedrooms * 10 + diningRooms * 20;
var totalPrice = 'Your price quote is: ' + total;
$("#output1").text(totalPrice).fadeIn();
});
I don't know if I got your question, but you can use $("#carpet_cleaning option:selected").val() to get the current selected value in a select component.
Fiddle: https://jsfiddle.net/7jrch7w6/4/
$("#carpet_cleaning").change(function () {
UpdateResult();
});
$("#dining_rooms").change(function () {
UpdateResult();
});
function UpdateResult()
{
var result = 'Your price quote is: ' + (($("#carpet_cleaning option:selected").val() * 10) + ($("#dining_rooms option:selected").val() * 20))
$("#output1").text(result).fadeIn();
}

Form field arrays validate individually with jQuery, but then form won't submit

This is my first post, so please be kind. :-)
I have a form with several arrays and other items. Some form fields can be entered more than once which is why they are arrays. I am using Jquery 1.11.1 and jquery validate. Two of my arrays are only required depending on a choice from a drop-down list. If the correct items are not filled in or selected, I get all of the error messages I expect. And, when all items are completed, all error messages are gone.
The problem is, the form will not then submit. I believe it has something to do with the "conditional" arrays because I have another form where the arrays are all required and it works fine.
This has been driving me crazy for a while now - long enough to post the question here. I have looked at many, many postings here and haven't found anyone with my exact problem.
I'm hoping someone can help.
Here is the HTML form (the JS and validation are included before the form):
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://ggsghpcc.sgt-inc.com/cmct/js/jquery.validate.js"></script>
<script language="JavaScript">
numComps = 1;
function showCampaigns(id) {
var mission1 = "missionOne";
var mission2 = "missionTwo";
var compNumber = id.slice(10);
var selection = document.getElementById(id).value;
if (selection == "missionOne") {
document.getElementById(selection + "_" + compNumber).style.display = "block";
document.getElementById(mission2 + "_" + compNumber).style.display = "none";}
if (selection == "missionTwo") {
document.getElementById(selection + "_" + compNumber).style.display = "block";
document.getElementById(mission1 + "_" + compNumber).style.display = "none"; }
}
$(document).ready(function() {
var u_campaignMissionOne = new Array;
var u_campaignMissionTwo = new Array;
var u_dataset = new Array;
var u_mission = new Array;
var FS = 1;
var x = 2;
var u_variable = new Array;
var u_intIndex = new Array;
$("#submitData").validate({
rules: {
'u_variable[]': {
required: true
},
'u_intIndex[]': {
required: true,
min: 1
},
'u_mission[]': {
required: true
},
'u_campaignMissionOne[]': {
required: function(element) {
var setNumber = $(element).attr('id');
var setNum = "comp" + setNumber.slice(21);
var missionNum = "u_mission_" + setNumber.slice(21);
return $((document.getElementById(missionNum).value) == 'MissionOne');
}
},
'u_campaignMissionTwo[]': {
required: function(element) {
var setNumber = $(element).attr('id');
var setNum = "comp" + setNumber.slice(21);
var missionNum = "u_mission_" + setNumber.slice(21);
return $((document.getElementById(missionNum).value) == 'MissionTwo');
}
},
'u_dataSet[]': {
required: true
}
},
messages: {
'u_variable[]': {
required:" Please enter a variable",
},
'u_intIndex[]': {
required:" Please enter a time interval",
},
'u_mission[]': {
required:" Please select a mission"
},
'u_campaignMissionOne[]': {
required:" Please select a Mission One campaign"
},
'u_campaignMissionTwo[]': {
required:" Please select a Mission Two campaign"
},
'u_dataSet[]': {
required:" Please select a data set"
}
},
wrapper: 'span',
errorPlacement: function (error, element) {
error.css({'padding-left':'10px','padding-top':'0.5em','padding-bottom':'2px', 'color': 'red', 'font-style':'italic', 'font-size':'14px', 'width': '330px', 'float': 'right'});
error.insertAfter(element);
}
});
});
</script>
<h2>Submit data</h2>
<div class="full-width-content-item">
<form id="submitData" action="alert.php" method="post" enctype="multipart/form-data">
<div>
<div id="formStuff" style="margin:0; padding:0; display:inline;">
<div style="height:40px; width:100%;"></div>
<div id="comp1">
<fieldset><legend>Data</legend>
<div id="intervalIndex">
<div class="fieldLabel"><label class="control-label">Time index*</label></div>
<input type="text" size="10" id="u_intIndex_1" name="u_intIndex[]" placeholder="Integer value > 0" value=""/>
</div><!--end intervalIndex--><br clear="right" />
<div id="variable">
<div class="fieldLabel"><label class="control-label">Variable*</label></div>
<input type="text" id="u_variable_1" name="u_variable[]" class="u_variable" value="" />
</div><!--end variable--><br clear="right" />
<div>
<div class="fieldLabel"><label class="control-label">Mission*</label> </div>
<select name="u_mission[]" id="u_mission_1" onchange="showCampaigns(this.id);">
<option value="">Please select</option>
<option value="missionOne" >Mission One</option>
<option value="missionTwo" >Mission Two</option>
</select>
</div><br clear="right" />
<div class="campaign">
<div class="missionOne" id="missionOne_1" style="height:3.0em; display:none;">
<div class="fieldLabel"><label class="control-label">Mission One Campaign*</label></div>
<select name="u_campaignMissionOne[]" id="u_campaignMissionOne_1" >
<option value="">Please select</option>
<option value="Campaign-MissionOne-1" >Campaign-MissionOne-1</option>
<option value="Campaign-MissionOne-2" >Campaign-MissionOne-2</option>
<option value="Campaign-MissionOne-3" >Campaign-MissionOne-3</option>
<option value="Campaign-MissionOne-4" >Campaign-MissionOne-4</option>
<option value="Campaign-MissionOne-5" >Campaign-MissionOne-5</option>
</select>
</div>
<div class="missionTwo" id="missionTwo_1" style="display:none;">
<div class="fieldLabel"><label class="control-label">Mission Two Campaign*</label></div>
<select name="u_campaignMissionTwo[]" id="u_campaignMissionTwo_1">
<option value="">Please select</option>
<option value="Campaign-MissionTwo-1" >Campaign-MissionTwo-1</option>
<option value="Campaign-MissionTwo-2" >Campaign-MissionTwo-2</option>
<option value="Campaign-MissionTwo-3" >Campaign-MissionTwo-3</option>
<option value="Campaign-MissionTwo-4" >Campaign-MissionTwo-4</option>
<option value="Campaign-MissionTwo-5" >Campaign-MissionTwo-5</option>
</select>
</div>
</div><!--end class=campaign--><br clear="right" />
<div>
<div class="fieldLabel"><label class="control-label">Data set*</label> </div>
<select name="u_dataSet[]" id="u_dataSet_1">
<option value="">Please select</option>
<option value="dataSet1" >dataSet 1</option>
<option value="dataSet2" >dataSet 2</option>
<option value="dataSet3" >dataSet 3</option>
<option value="dataSet4" >dataSet 4</option>
<option value="dataSet5" >dataSet 5</option>
</select>
</div><br clear="right" />
</fieldset></div><!--end comp1 div-->
<div style="height:40px; width:100%;"></div>
<div id="comp2">
<fieldset><legend>Data</legend>
<div id="intervalIndex">
<div class="fieldLabel"><label class="control-label">Time index*</label></div>
<input type="text" size="10" id="u_intIndex_2" name="u_intIndex[]" placeholder="Integer value > 0" value=""/>
</div><!--end intervalIndex--><br clear="right" />
<div id="variable">
<div class="fieldLabel"><label class="control-label">Variable*</label></div>
<input type="text" id="u_variable_2" name="u_variable[]" value="" />
</div><!--end variable--><br clear="right" />
<div>
<div class="fieldLabel"><label class="control-label">Mission*</label></div>
<select name="u_mission[]" id="u_mission_2" onchange="showCampaigns(this.id);">
<option value="">Please select</option>
<option value="missionOne" >Mission One</option>
<option value="missionTwo" >Mission Two</option>
</select>
</div><br clear="right" />
<div class="campaign">
<div class="missionOne" id="missionOne_2" style="height:3.0em; display:none;">
<div class="fieldLabel"><label class="control-label">Mission One Campaign*</label></div>
<select name="u_campaignMissionOne[]" id="u_campaignMissionOne_2" >
<option value="">Please select</option>
<option value="Campaign-MissionOne-1" >Campaign-MissionOne-1</option>
<option value="Campaign-MissionOne-2" >Campaign-MissionOne-2</option>
<option value="Campaign-MissionOne-3" >Campaign-MissionOne-3</option>
<option value="Campaign-MissionOne-4" >Campaign-MissionOne-4</option>
<option value="Campaign-MissionOne-5" >Campaign-MissionOne-5</option>
</select>
</div>
<div class="missionTwo" id="missionTwo_2" style="display:none;">
<div class="fieldLabel"><label class="control-label">Mission Two Campaign*</label></div>
<select name="u_campaignMissionTwo[]" id="u_campaignMissionTwo_2">
<option value="">Please select</option>
<option value="Campaign-MissionTwo-1" >Campaign-MissionTwo-1</option>
<option value="Campaign-MissionTwo-2" >Campaign-MissionTwo-2</option>
<option value="Campaign-MissionTwo-3" >Campaign-MissionTwo-3</option>
<option value="Campaign-MissionTwo-4" >Campaign-MissionTwo-4<option>
<option value="Campaign-MissionTwo-5" >Campaign-MissionTwo-5<option>
</select>
</div>
</div><!--end class=campaign--><br clear="right" />
<div>
<div class="fieldLabel"><label class="control-label">Data set*</label></div>
<select name="u_dataSet[]" id="u_dataSet_2">
<option value="">Please select</option>
<option value="dataSet1" >dataSet 1</option>
<option value="dataSet2" >dataSet 2</option>
<option value="dataSet3" >dataSet 3</option>
<option value="dataSet4" >dataSet 4</option>
<option value="dataSet5" >dataSet 5</option>
</select>
</div><br clear="right" />
</fieldset></div><!--end comp2 div-->
<div style="height:20px; width:100%;"></div>
<button type="submit" >Submit</button></div>
</form>

Categories

Resources