Selected option disappears when button is pressed - javascript

I have a file, template.php, which contains a JS function to add some dropdown box options to the page, so the user can add as many more options as they wish.
My issue is, if the user has selected some options within those select boxes, and then presses the "addsunday" button to add more boxes, the previously chosen options are cleared (so every dropdown on the page resets to 00:00).
I'd like to know what is causing the selections to reset and how I can get around this problem.
$("#addsunday").click(function() {
var htmlstring = "<div class='shiftwrapper'>";
htmlstring += "<select data-col-id='start' form='newtemplateform'>";
htmlstring += "<?php
for($hours=0; $hours<24; $hours++) // the interval for hours is '1'
for($mins=0; $mins<60; $mins+=30) // the interval for mins is '30'
echo '<option>'.str_pad($hours,2,'0',STR_PAD_LEFT).':'
.str_pad($mins,2,'0',STR_PAD_LEFT).'</option>';?>";
htmlstring += "</select>";
htmlstring += "<select data-col-id='finish' form='newtemplateform'>";
htmlstring += "<?php
for($hours=0; $hours<24; $hours++) // the interval for hours is '1'
for($mins=0; $mins<60; $mins+=30) // the interval for mins is '30'
echo '<option>'.str_pad($hours,2,'0',STR_PAD_LEFT).':'
.str_pad($mins,2,'0',STR_PAD_LEFT).'</option>';?>";
htmlstring += "</select>";
htmlstring += "<select data-col-id='loc' form='newtemplateform'>";
htmlstring += "<?php foreach($locations as $location){ print '<option value=\"$location\">' . $location . '</option>\n'; }?>";
htmlstring += "</select>";
htmlstring += "<button class='removeshift'>Remove Shift</button><br/>";
htmlstring += "</div>";
document.getElementById('sundaywrap').innerHTML += htmlstring;
console.log("Sunday clicked");
});
I apologise if this is a really inefficient way to repeat code, I'm still learning.
Here's a really bad fiddle: https://jsfiddle.net/L7npxvzp/
It doesn't work however you can see the structure of how the dropdowns work. There's a button to add more dropdowns, it is when this button is pressed that the previously changed selections reset back to their defaults.

The problem is this line:
document.getElementById('sundaywrap').innerHTML += htmlstring;
This replaces the DOM elements in #sundaywrap with new DOM elements that come from parsing the HTML after you've concatenated htmlstring. Any dynamic state in the old DOM elements, such as selected items from a menu, is lost.
Instead of concatenating to the HTML, you should append to the DOM:
$("#sundaywrap").append(htmlstring);

Related

Get id from foreach loop javascript

After looping the delete button, I've been trying to get the id so that I can use it with the onclick function but no luck yet.
var table = "";
res.data.forEach((value, key) => {
table += "<tr>";
table += "<td>"+value.post_held+"</td>";
table += "<td>"+value.established_officer+"</td>";
table += "<td>"+value.date_of_commencement+"</td>";
table += "<td>"+value.date_of_termination+"</td>";
table += "<td><button id=career"+value.id+" class='btn btn-danger'>Delete</button></td>";
table += "</tr>";
var career = document.querySelector("#career"+value.id);
career.addEventListener("click",()=>{
alert("done")
})
});
I think maybe you forgot to add table to DOM.
You just create a string value which contain html code, but you didn't add this html code into the DOM, so you can not find this DOM element by id.
You can use insertAdjacentHTML method to add this element which you want to DOM

how to get the value of dynamically created selectbox

I am creating a div dynamically with ajax. Now if the ajax call is success then i created a string for div element and append it to the original div id.
here is my code
$.ajax({
type:"GET",
url:"resources/json/asnData.json",
dataType:"json",
success:function(data){
$.each(data.Payload, function(index, val){
i=i+1;
stmt+='<div class="row">'+
'<section class="col col-2">'+
'<label class="input"><i class="icon-append fa fa-key"></i>'+
'<input type="text" name="keyName" value="'+val.key+'" readonly/>'+
'</label>'+
'</section>'+
'<section class="col col-3">'+
'<label class="select">'+
'<select id="dataConversionType'+i+'" class="dataConversionType">'+
'<option value="HEX">HEX</option>'+
'<option value="ALL">Compare All</option>'+
'<option value="ASCII">ASCII</option>'+
'<option value="STRING">STRING</option>'+
'<option value="INT">INTEGER</option>'+
'<option value="BINT">BIG INTEGER</option>'+
'</select><i></i>'+
'</label>'+
'</section>'+
'<section class="col col-5">'+
'<label class="input"><i class="icon-append fa fa-dashcube "></i>'+
'<input id="convertedType'+i+'" type="text" value="'+val.value+'" readonly/>'+
'</label>'+
'</section>'+
'</div>';
});
$(".dataParser").append(stmt);
Now there is function where if someone select a value in selectbox then fire and show.
$('#dataConversionType'+i).change(function(e) {
e.preventDefault();
var conversionType=$(this).val(); //I have doubt here also..
console.log(conversionType);
if(conversionType == 'ALL') {
console.log('ALL-Show a modal with each possible conversion');
}
but this is not working. this function works if I called using the class name. But i have to call the function using id with the i value, so that with that i value i can also set some value in other fields.
any help will be appreciated...
Use class instead of id (replace document with some non dynamic container)
$(document).on('change','.dataConversionType',function(e) {
e.preventDefault();
var conversionType=$(this).val();
console.log(conversionType);
var index_val = $(this).attr('data-index')
if(conversionType == 'ALL') {
console.log('ALL-Show a modal with each possible conversion');
}
)};
And when you are generating your element add a data attribute
'<select id="dataConversionType'+i+'" class="dataConversionType" data-index="'+i+'">'
Also if you are inside a loop you need to wrap your ajax within a closure if you want to get correct value and not the latest one.
(function(idx) {
//ajax stuff here
}(i)
Do one thing, Listen to the change event using class name itself, instead of Id.
Put value of i as a custom attribute into the select box. In the listener function, read this attribute and call or perform whatever actions you have to do.
A sample is as below:
'<section class="col col-3">'+
'<label class="select">'+
'<select id="dataConversionType'+i+'" class="dataConversionType" data-count=i>'+
'<option value="HEX">HEX</option>'+
'<option value="ALL">Compare All</option>'+
'<option value="ASCII">ASCII</option>'+
'<option value="STRING">STRING</option>'+
'<option value="INT">INTEGER</option>'+
'<option value="BINT">BIG INTEGER</option>'+
'</select><i></i>'+
'</label>'+
'</section>'
Event listener:-
$('.dataConversionType').change(function(e) {
e.preventDefault();
var conversionType=$(this).val(); //selected value
var valueofI = $(this).attr("data-count");// Value of i
}
data-count is the custom attribute.
Try On change method
$(document).on('change','.dataConversionType',function(e) {
// Paste Your Code
});
OR
$(document).on('change','#dataConversionType',function(e) {
// Paste Your Code
});
$('#dataConversionType1').change(function(e) {alert("Changed")});
this code will not work for dynamically append select box.
you should try-
$(document).on("change","#dataConversionType1",function(){
alert($('#dataConversionType1 option:selected').val());
});
This works for me.
The value of i has been now changed to the latest one and this would not give you all the selectboxes anyways.
If you want to be specific about any select box, do it like:
$('#dataConversionType1').change(function(e) {
// code here
});
If you want to do something on all the selectboxes you have created, you can do it like:
$('[id^="dataConversionType"]').change(function (e) {
// Find the index: Count of i
var elmIndex = $(this).attr("id").replace("dataConversionType", "");
// Reflects the value of it in related input field
$("#convertedType3" + elmIndex).val($(this).val());
});
If you want to use the value of i later for operations, you can do it in 2 ways:
set the value of i in some data- attribute like: data-index=i (example below):
'<select id="dataConversionType'+i+'" class="dataConversionType" data-index="' + i + '">'+
Get the index from the id itself doing split or regex (example: /\d/).

show div based on textbox value

I have a input field that gets it value from a db lets say the value is M,K,H,J,V or G depending on the value it needs to open the div with aaa,bbb,ccc,ddd,eee or fff as text.
The code that is displayed on the page is as followed i left out the retrieval part from the db that part is working (the input box shows M,K,H,J,V or G depending on the id.)
echo "<input type='text' name='periode' id='periode' data-related-item='" .$row['periode']. "' value='" .$row['periode']. "'>";
echo "<div class='hidden'><div id='M'>aaa</div></div>";
echo "<div class='hidden'><div id='K'>bbb</div></div>";
echo "<div class='hidden'><div id='H'>ccc</div></div>";
echo "<div class='hidden'><div id='J'>ddd</div></div>";
echo "<div class='hidden'><div id='V'>eee</div></div>";
echo "<div class='hidden'><div id='G'>fff</div></div>";
When i check the source code in developer mode it shows that the data-related-item part is correctly retrieved from the db:
<input type="text" name="periode" id="periode" data-related-item="M" value="M">
I want to use the following JS but i need to change it to work with textboxes.
<script type="text/javascript">
function evaluate1(){
var item = $(this);
var relatedItem = $("#" + item.attr("data-related-item")).parent();
if(item.is(":checked")){
relatedItem.fadeIn();
}else{
relatedItem.fadeOut();
}
}
$('input[type="checkbox"]').click(evaluate1).each(evaluate1);
</script>
The simplest approach is offcourse changing:
$('input[type="checkbox"]').click(evaluate1).each(evaluate1);
into
$('input[type="textbox"]').click(evaluate1).each(evaluate1);
But what do i need to do with:
if(item.is(":checked")){
Thanks for any help in advance.
I tried the following but it aint working.
if(item.is("M||K||H||J||V||G")){
SOLUTION BY ROBERT ROZAS
The solution is in jsfiddle
http://jsfiddle.net/dXTtz/7/
I made this code based on the code you provide:
$(document).ready(function(){
$("#periode").keyup(function(){
var valor = $("#periode").val();
$(".hidden").each(function(){
var hijo = $(this).children().attr('id');
if(hijo == valor)
{
$(this).removeClass("hidden");
}
});
});
});
Working fiddle here: http://jsfiddle.net/robertrozas/dXTtz/2/
This way is working on page load: http://jsfiddle.net/robertrozas/dXTtz/4/
Page load and removing the extra hidden divs: http://jsfiddle.net/dXTtz/5/

Add i++ for each new row that will created by the button

I try to make some repeatable fields with PHP and Javascript. This works fine, but after saving the post (creating an plugin for WordPress) the cloned row will override the latest one. This is because I don't use unique id's for each row.
I want to add an 'id' attribute with javascript and I want for each row that is created with the id 1 increase. I had already done something similar with PHP, but found out that this is not what I wanted and I am better out with javascript, I think, because when I clone the field with the "add new" button the amount doesn't increase with +1;
Here is the php code that I had used:
$count = 2;
for ($i = 0; $i < $count; $i++) {
// Begin a table row
echo '<tr class="row" id="' . '['.$i.']' . '-repeatable">';
echo '<td class="order">' . '['.$i.']' . '</td>';
// Do cool stuff inside the row
echo '<td class="remove"><a class="repeatable-remove button" href="#">-</a></td>';
echo '</tr>'; // End .row
} // End for loop
<a href"#" class="button">Add new row</a>
JS code for the repeatable fields:
// Add repeatable row
jQuery('.repeatable-add').click(function() {
// Clone row
var row = jQuery(this).closest('.ui-sortable').find('tbody tr.row:last-child');
var clone = row.clone();
clone.find('input[type=text], text, textarea, select, input.upload_image').val(''); // Reset the values
clone.find('.preview_image').attr('src', ''); // Reset the values
row.after(clone);
//
return false;
});
I think I have to do something like this snippet of line:
clone.find('tr.row').attr('id', 'repeatable-' + addInteger);
But how do I increase with +1 inside Jquery/Javascript, like my example in PHP?
What you want to do is look at the ID of the row you're cloning and use that ID to give the new row its proper index value. I added two lines of code to your example, one defining a new variable called clonedIdIndex and one using the value in that variable to define a new ID for the cloned row.
jQuery('.repeatable-add').click(function() {
// Clone row
var row = jQuery(this).closest('.ui-sortable').find('tbody tr.row:last-child'),
clone = row.clone(),
clonedIdIndex = parseInt( clone.find('tr.row').attr('id').split('-')[1], 10 );
clone.find('input[type=text], text, textarea, select, input.upload_image').val('');
clone.find('.preview_image').attr('src', ''); // Reset the values
// Assign new ID
clone.find('tr.row').attr('id', 'repeatable-' + (++clonedIdIndex));
row.after(clone);
//
return false;
});

Execute a Javascript function from a button in a table row cell which was generated by PHP echo

I want to call a Javascript function from a table row cell.
I need to pass the id of that row as well.
In one cell I use an href (which does popup my edit dialog), but does not pass the Id (BrId).
The next one, well ideally a button which invokes a Javascript function (though I've seen code/functions which associates a click event function within $(document).ready(function() {.....etc}) but unsure if this will pick up the required Id (BrId) which is a primary key to a database table.
Code is:
foreach ($myrows as $row) {
echo "<tr>";
echo '<td style="border:none;">' .$row->BrId. '</td>';
echo '......'
echo '......'
echo '<td style="border:none;"><a href="#dialog" name="modal">Edit this branch </td>';
echo '<td style="border:none;"><button onclick="EditBranch (1)"></td>';
}
Ideally the function would also show my popup div ( id= dialog ) as the "a href="#dialog" name="modal" does.
If this helps, here's a section of the script:
$(document).ready(function() {
//select all the a tags with name equal to modal
$('a[name=modal]').click(function(e) {
//Cancel the link behavior
e.preventDefault();
//Get the A tag
var id = $(this).attr('href'); //gets me my div id
//other code for transition effects and positioning of my div....
}
You can pass the row id through a custom html data attribute :
echo ' Edit this branch ';
Then, you simply retrieve it like that :
var id = $(this).attr('data-id');

Categories

Resources