I am trying to send the value of the selected option to an new DIV to dynamic load an drop down menu.
The DIV is triggered but the needed value is not send to this new DIV.
The problem is + $("#add_bedrijf_" + [i]).val()
What is the correct wat to send this?
(The other code is for manipulating the different classes, this is working correct.)
<div class="form-group col-md-6">
<div class="form-group has-warning-add has-feedback" id="div_add_bedrijf" data-toggle="buttons">';
$c = 0;
foreach ($_SESSION['bedrijf'] as $value)
{
echo '<label class="btn btn-secondary" for="add_bedrijf_<?php echo $c;?>"><input type="radio" id="add_bedrijf_<?php echo $c;?>" name="add_bedrijf" value="'.$value.'" onmousemove="validate_add()" onblur="validate_add()"><img src="images/logo_'.$value.'_small.png" height="30"></label>';
$c++;
}
echo '<span class="glyphicon glyphicon-warning-sign form-control-feedback" id="add_bedrijf_status"></span>
</div>
</div>
<script type="text/javascript">
function validate_add()
{
// Parent div of all buttons
let div_add_bedrijf = document.getElementById('div_add_bedrijf');
// Status div
let add_bedrijf_status = document.getElementById('add_bedrijf_status');
// A list with all the inputs that start the with id "add_bedrijf_"
let elements = document.querySelectorAll('input[id^="add_bedrijf_"]');
for(let i = 0; i < elements.length; i++) {
let element = elements[i];
// If the element is checked
if(element.checked) {
div_add_bedrijf.className = "form-group has-success has-feedback";
add_bedrijf_status.className = "glyphicon glyphicon-ok form-control-feedback";
$("#add_groep").load("includes/dynamic_drop/magazijn_magazijn_groep.php?choice=" + $("#add_bedrijf_" + [i]).val())
// We found one was selected, so exit the loop
return;
} else {
div_add_bedrijf.className = "form-group has-warning has-feedback";
add_bedrijf_status.className = "glyphicon glyphicon-warning-sign form-control-feedback";
}
}
}
</script>
Did you try + element.value instead of + $("#add_bedrijf_" + [i]).val()?
https://www.w3schools.com/jsref/prop_radio_value.asp
Related
So, I'm trying to create a filter for this list of stores, so only the ones with content that is equal to the value of the input box will display. Unfortunately, my filter does not work correctly. For one, whatever I type in the input box causes all of my store elements to add the 'display' class, which causes my items to receive the style 'display: none;'. Secondly, it's not updating every time a key is pressed.
HTML:
<li class="p-3 clearfix store display">
<div class='float-left w-50'>
<div class='mb-1'><strong>Store Number:</strong><span class="store-info">
<?php
if (strlen($row['store_num']) < 4) {
if (strlen($row['store_num']) == 3) {
echo '0' . $row['store_num'];
} else if (strlen($row['store_num']) == 2) {
echo '00' . $row['store_num'];
}
} else {
echo $row['store_num'];
}
?>
</span></div>
<div class='mb-1'><strong>Store Name: </strong><span class='store-info'><?php echo $row['store_name']; ?></span></div>
<div class='clearfix mb-1'>
<p class='float-left'><strong>Address: </strong></p>
<span class='d-block store-info float-left'><?php echo $row['store_street']; ?></span>
<br>
<span class='d-block store-info float-left'><?php echo $row['store_city']; ?>, <?php echo strtoupper($row['store_state']); ?> <?php echo $row['store_zip']; ?></span>
</div> <!-- mb-1 -->
</div> <!-- float-left -->
<div class="float-left w-50 clearfix">
<div class="d-inline float-right">
<div class='mb-1'>
<strong>Time Zone: </strong><span class='time-zone store-info'><?php echo strtoupper($row['time_zone']); ?></span>
</div>
<div class='mb-1'>
<strong>Current Time: </strong><time>3:45pm</time>
</div>
<div class='mb-1'>
<strong>Phone Number:</strong><span class='store-info'>
<?php
$phone = $row['store_phone'];
$area = substr($phone, 0, 3);
$prefix = substr($phone, 4, 3);
$line = substr($phone, 6, 4);
echo '(' . $area . ') ' . $prefix . '-' . $line;
?>
</span>
</div>
<div class='mb-1'>
<strong>Fax Number:</strong><span class='store-info'>
<?php
$phone = $row['store_fax'];
$area = substr($phone, 0, 3);
$prefix = substr($phone, 4, 3);
$line = substr($phone, 6, 4);
echo '(' . $area . ') ' . $prefix . '-' . $line;
?>
</span>
</div>
</div> <!-- d-inline -->
</div> <!-- float-right -->
</li> <!-- clearfix -->
JavaScript:
var search = document.getElementById('search');
var stores = document.querySelectorAll('.store');
search.addEventListener('keyup', function (e) {
var data = e.target.value.toLowerCase();
stores.forEach(function(store) {
var spans = document.querySelectorAll('.store-info');
for(var i = 0; i < spans.length; i++) {
if (spans[i].innerText.toLowerCase() != data) {
store.classList.remove('display');
} else {
store.classList.add('display');
}
}
});
});
If I understand your question correctly, you could make the following changes to your javascript to resolve the issues you're facing. Please see comments in code for explaination of what's going on:
search.addEventListener('keyup', function (e) {
var query = e.target.value.toLowerCase();
if (search.value.length >= 0) {
search.classList.add('focused');
label.classList.add('focused');
} else {
search.classList.remove('focused');
label.classList.remove('focused');
}
// recommend performing this query in the keyup event to ensure
// that you're working with the most up to date state of the DOM
var stores = document.querySelectorAll(".store");
stores.forEach(function(store) {
// query .store-info from current store
var spans = store.querySelectorAll(".store-info");
// hide the store by default
store.style.display = 'none';
for (var i = 0; i < spans.length; i++) {
var storeInfoText = spans[i].innerText.toLowerCase();
// consider revising search logic like so
if (storeInfoText.indexOf(query) !== -1 || !query) {
// display the store if some match was found
store.style.display = 'block';
}
}
});
});
Link to working jsFiddle here
I think your issue with it showing everything is because of the add remove... if a store already has display it will re add it and then only remove it once where as if it doesn’t you will get an error so try toggle
var search = document.getElementById('search');
var stores = document.querySelectorAll('.store');
search.addEventListener('keyup', function (e) {
var data = e.target.value.toLowerCase();
stores.forEach(function(store) {
var spans = document.querySelectorAll('.store-info');
spans.filter(span=>{
if(span.innerText.toLowerCase().includes(data)){
store.classList.toggle('display');
}else{store.classList.toggle('display')
})
});
I am dividing my webpage in two vertical parts. Where left panel is used to render a list of categories of books and right panel is used for rendering books associated with selected category. We also have buttons to hide a specific category from left side.
<div class="content">
<div class='col-3'>
<h3> Category </h3>
<div class="category-container dev-category-list">
</div>
</div>
<div class='col-9'>
<h3> Books </h3>
<div class="books-container dev-books-list">
</div>
</div>
</div>
Javascript Code:
var categories = ['category-1','category-2','category-3','category-4','category-5','category-6','category-7'];
var books = {'cat1':['1984','Dracula','Twilight','Holes','Homes','Uglies','Othello'],'cat2':['Dracula','Twilight','1984','Holes','Homes','Uglies','Othello'],'cat3':['1984','Twilight','Holes','Homes','Dracula','Uglies','Othello'],'cat4':['Othello','1984','Dracula','Uglies','Holes','Twilight','Eclipse'],'cat5':['Hamlet','Macbeth','Othello','Holes','Night','Twilight','Eclipse'],'cat6':['1984','Hamlet','Dracula','Uglies','Othello','Night','Twilight'],'cat7':['1984','Hamlet','Macbeth','Uglies','Othello','Holes','Night']};
setup_UI_elements();
function setup_UI_elements(){
appendCategories();
renderBooks('1');
addCategListner();
addBtnListner();
}
function appendCategories(){
container = $('.dev-category-list');
for(var i=0; i< categories.length; i++){
categHtml = "<div data-categ-id='"+ (i+1) + "' class='categ'> "+categories[i]+" </div>";
container.append(categHtml)
}
}
function renderBooks(categ_id){
container = $('.dev-books-list');
container.html('');
categ_key = 'cat'+categ_id
$('.categ').removeClass('selected');
$('div.categ[data-categ-id='+categ_id+']').addClass('selected');
for(var i=0; i< books[categ_key].length; i++){
bookHTML = "<div data-book-id='"+ (i+1) + "' class='book'> "+books[categ_key][i];
bookHTML += "<button type='button' data-book-id='"+ (i+1) + "' data-categ-id='"+ (books[categ_key].length-i) + "' class='btn'> Hide Categ "+ (books[categ_key].length-i) +"</button> </div>";
container.append(bookHTML);
}
}
function addCategListner(){
container = $('.dev-category-list');
container.click(function(e){
target = $(e.target);
$('.categ').removeClass('selected hidden');
target.toggleClass('selected');
categ_id = target.data('categ-id');
renderBooks(categ_id);
});
}
function addBtnListner(){
container = $('.dev-books-list');
container.click(function(e){
target = $(e.target);
if(target.hasClass('btn')){
categ_id = target.data('categ-id');
target.toggleClass('added');
if(target.hasClass('added'))
target.html('Show Categ'+categ_id)
else
target.html('Hide Categ'+categ_id)
categDiv = $('.dev-category-list div[data-categ-id='+categ_id+']')
categDiv.toggleClass('hidden');
}
});
}
When I try to hide a category from left panel which is no longer in above the fold then it is scrolling right panel instead of left panel.
I works fine in Firefox and Safari.
JS Bin: https://jsbin.com/bafasoy/edit?html,js,output
I have form which gets clone when user click on add more button .
This is how my html looks:
<div class="col-xs-12 duplicateable-content">
<div class="item-block">
<button class="btn btn-danger btn-float btn-remove">
<i class="ti-close"></i>
</button>
<input type="file" id="drop" class="dropify" data-default-file="https://cdn.example.com/front2/assets/img/logo-default.png" name="sch_logo">
</div>
<button class="btn btn-primary btn-duplicator">Add experience</button>
...
</div>
This my jquery part :
$(function(){
$(".btn-duplicator").on("click", function(a) {
a.preventDefault();
var b = $(this).parent().siblings(".duplicateable-content"),
c = $("<div>").append(b.clone(true, true)).html();
$(c).insertBefore(b);
var d = b.prev(".duplicateable-content");
d.fadeIn(600).removeClass("duplicateable-content")
})
});
Now I want every time user clicks on add more button the id and class of the input type file should be changed into an unique, some may be thinking why I'm doing this, it I because dropify plugin doesn't work after being cloned, but when I gave it unique id and class it started working, here is what I've tried :
function randomString(len, an){
an = an&&an.toLowerCase();
var str="", i=0, min=an=="a"?10:0, max=an=="n"?10:62;
for(;i++<len;){
var r = Math.random()*(max-min)+min <<0;
str += String.fromCharCode(r+=r>9?r<36?55:61:48);
}
return str;
} var ptr = randomString(10, "a");
var className = $('#drop').attr('class');
var cd = $("#drop").removeClass(className).addClass(ptr);
Now after this here is how I initiate the plugin $('.' + ptr).dropify().
But because id is still same I'm not able to produce clone more than one.
How can I change the id and class everytime user click on it? is there a better way?
Working Fiddle.
Problem :
You're cloning a div that contain already initialized dropify input and that what create the conflict when you're trying to clone it and reinitilize it after clone for the second time.
Solution: Create a model div for the dropify div you want to clone without adding dropify class to prevent $('.dropify').dropify() from initialize the input then add class dropify during the clone.
Model div code :
<div class='hidden'>
<div class="col-xs-12 duplicateable-content model">
<div class="item-block">
<button class="btn btn-danger btn-float btn-remove">
X
</button>
<input type="file" data-default-file="http://www.misterbilingue.com/assets/uploads/fileserver/Company%20Register/game_logo_default_fix.png" name="sch_logo">
</div>
<button class="btn btn-primary btn-duplicator">Add experience</button>
</div>
</div>
JS code :
$('.dropify').dropify();
$("body").on("click",".btn-duplicator", clone_model);
$("body").on("click",".btn-remove", remove);
//Functions
function clone_model() {
var b = $(this).parent(".duplicateable-content"),
c = $(".model").clone(true, true);
c.removeClass('model');
c.find('input').addClass('dropify');
$(b).before(c);
$('.dropify').dropify();
}
function remove() {
$(this).closest('.duplicateable-content').remove();
}
Hope this helps.
Try this:
$(function() {
$(document).on("click", ".btn-duplicator", function(a) {
a.preventDefault();
var b = $(this).parent(".duplicateable-content"),
c = b.clone(true, true);
c.find(".dropify").removeClass('dropify').addClass('cropify')
.attr('id', b.find('[type="file"]')[0].id + $(".btn-duplicator").index(this)) //<here
$(c).insertBefore(b);
var d = b.prev(".duplicateable-content");
d.fadeIn(600).removeClass("duplicateable-content")
})
});
Fiddle
This does what you specified with an example different from yours:
<div id="template"><span>...</span></div>
<script>
function appendrow () {
html = $('#template').html();
var $last = $('.copy').last();
var lastId;
if($last.length > 0) {
lastId = parseInt($('.copy').last().prop('id').substr(3));
} else {
lastId = -1;
}
$copy = $(html);
$copy.prop('id', 'row' + (lastId + 1));
$copy.addClass('copy');
if(lastId < 0)
$copy.insertAfter('#template');
else
$copy.insertAfter("#row" + lastId);
}
appendrow();
appendrow();
appendrow();
</script>
Try adding one class to all dropify inputs (e.g. 'dropify'). Then you can set each elements ID to a genereted value using this:
inputToAdd.attr('id', 'dropify-input-' + $('.dropify').length );
Each time you add another button, $('.dropify').length will increase by 1 so you and up having a unique ID for every button.
I have a submit button which I am sharing between 'Create' and 'Update'. I want the following labels depending on my page state:
Create = Submit
Update = Update
These buttons also have an image at the front of them using glyphicon but the image will be the same for both buttons.
To get to my page states (listed above) I have other JavaScript functions which the relevant buttons call.
All my code is below. I am struggling as I am fairly new to JavaScript and I now I can do it by adding using Value but this doesn't work due to my image.
Edit Button HTML
<button type="button"class="btn btn-default" name="RegCashMove_Edit_Button" onclick='RegCashMoveEdit()'>
<span class="glyphicon glyphicon-pencil" title="Edit" style="vertical-align: middle"></span>
</button>
Create Button HTML
<button type="button" class="btn btn-default" name="RegCashMove_Create_Button" onclick='RegCashMoveCreate()'>
<span class="glyphicon glyphicon-plus"></span> Create
</button>
Variable Button HTML
This is the button I want the label to be variable on. At the moment its 'Submit'
<button name="RegularCashMovements_Submit_Button" class="btn btn-default" id="RegularCashMovements_Submit_Button" type="submit">
<span class="glyphicon glyphicon-ok"></span> Submit
</button>
JavaScript function for 'Create' button
function RegCashMoveCreate(txt) {
document.getElementById('selection').value = "Create";
document.getElementById('index').value = "";
document.getElementById('RCMViewState').value = "Initial";
document.getElementById('submitAndCancel').style.display = "block";
document.getElementById('editAndConfirm').style.display = "none";
document.getElementById('yesAndNo').style.display = "none";
document.getElementById('confirmTemplate').style.display = "none";
document.getElementById('createEditDeleteTopLine').style.display = "block";
document.getElementById('RegCashMoveHeading').innerHTML = "<h3>" + txt + "</h3>";
document.getElementById('RegCashMoveFields').style.display = "block";
document.getElementById('RegCashMoveDeleteConfirmation').style.display = "none";
document.getElementById('FromDiv').innerHTML = "<%=fromInnerHtml%>";
document.getElementById('ToDiv').innerHTML = "<%=toInnerHtml%>";
document.getElementById('AmountDiv').innerHTML = "<%=amountInnerHtml%>";
document.getElementById('FrequencyDiv').innerHTML = "<%=frequencyInnerHtml%>";
document.getElementById('FromErrorDiv').innerHTML = "";
document.getElementById('ToErrorDiv').innerHTML = "";
document.getElementById('AmountErrorDiv').innerHTML = "";
document.getElementById('FrequencyErrorDiv').innerHTML = "";
document.getElementById('RegCashMove_From_DropDownList').value = "- - Please select - -";
document.getElementById('RegCashMove_To_DropDownList').value = "- - Please select - -";
document.getElementById('RegCashMove_Amount_TextBox').value = "";
document.getElementById('RegCashMove_Frequency_DropDownList').value = "0";
};
JavaScript function for 'Edit' button
function RegCashMoveEdit(txt, from, to, amount, frequency, index) {
document.getElementById('selection').value = "Edit"
document.getElementById('index').value = index;
document.getElementById('RCMViewState').value = "Initial";
document.getElementById('submitAndCancel').style.display = "block";
document.getElementById('editAndConfirm').style.display = "none";
document.getElementById('yesAndNo').style.display = "none";
document.getElementById('confirmTemplate').style.display = "none";
document.getElementById('createEditDeleteTopLine').style.display = "block";
document.getElementById('RegCashMoveHeading').innerHTML = "<h3>" + txt + "</h3>";
document.getElementById('RegCashMoveFields').style.display = "block";
document.getElementById('RegCashMoveDeleteConfirmation').style.display = "none";
document.getElementById('FromDiv').innerHTML = "<%=fromInnerHtml%>";
document.getElementById('ToDiv').innerHTML = "<%=toInnerHtml%>";
document.getElementById('AmountDiv').innerHTML = "<%=amountInnerHtml%>";
document.getElementById('FrequencyDiv').innerHTML = "<%=frequencyInnerHtml%>";
document.getElementById('FromErrorDiv').innerHTML = "";
document.getElementById('ToErrorDiv').innerHTML = "";
document.getElementById('AmountErrorDiv').innerHTML = "";
document.getElementById('FrequencyErrorDiv').innerHTML = "";
document.getElementById('RegCashMove_From_DropDownList').value = from;
document.getElementById('RegCashMove_To_DropDownList').value = to;
document.getElementById('RegCashMove_Amount_TextBox').value = amount;
document.getElementById('RegCashMove_Frequency_DropDownList').value = frequency;
};
I no I should be able to add a variable in each of my JavaScript function to display the relevant label but my issue is getting it on the button with my image
You can set the textual content of a HTML element with the "textContent" property ("innerText" in IE < 9):
var button = document.getElementById('RegularCashMovements');
button.innerText = button.textContent = 'new text';
The span element inside the button element should not be removed.
If you also want to change the title of the span do it like that:
for (var index = 0; index < button.childNodes.length; index++) {
if (button.childNodes[index].tagName == 'SPAN') {
button.childNodes[index].title = 'new title';
break;
}
}
You need to iterate through all child nodes of the button, instead of taking the first one, because than you will get the text content of the button again.
I hope i understood your problem. I also have to say, that your javascript is very procedural and inperformant because of all the "display: none;" and innerHTML accesses. My tip for you would be to think more objective and put all elements you need to hide in one container element and hide that one.
I am trying to create an event listener across a bunch of links on my site. These links are generated within a loop, so I end up with <a class = "replyButton" id = "replyID"<? echo $x; ?> etc.
I'm trying to use the code below to reveal an input box when each respective link is clicked, but with no luck. I can get it to work using plain JS too, in one case, but not using JQuery, extrapolated across several like this. Any help would be really awesome.
window.onload = function(){
$('.replyButton').each(function(index){
var domElementId = "replyArea" + index;
domElementId.onclick = function() {
var replyFieldHtml = '<div class = "span4" id = "replyTextField"><table><tr><td id = "replyPhoto"><img src = "/assets/img/usr/profile_holder.jpg" /></td><td id = "replyContent"><input type = "text" id = "replyInput" onkeydown="if (event.keyCode == 13) wallReply()" placeholder = "leave a reply..." /></td></tr></table></div>';
document.getElementById('domElementId').innerHTML = replyFieldHtml;
console.log('domElementId');
return false;
}
});
}
Edit: here is the loop im using to generate the html...
$x = 0;
while ($x < 8){
$x++;
$r = $wallarray - $x;
$postContent = $wall_content['wall_posts'][$x-1];
$postUser = getUserNameById($wall_content['userID'][$x-1]);
?>
<div class = "row">
<div class = "span6">
<div class = "span1" id = "wallPhoto"><img src ="assets/img/usr/profile_holder.jpg></div>
<div class = "span4">
<div class = "span4" id = "wallFeedStyle"><a id = "wallUserLink" href = "#"><b><? echo $postUser; ?></b></a></div>
<div class = "row">
<div class = "span5">
<div class = "span4" id = "userPost"><? echo $postContent; ?></br><p class = "wallsmall"></i>Like ·<a class = "replyButton" id = "replyButton<? echo $x; ?>" href="#"></i>Reply</a></p></div></div>
</div>
<div class = "row">
<div class = "span5">
</div>
</div>
<div class = "row" id = "replyArea<? echo $x; ?>"></div>
</div>
<?
}
?>
You're using the variable in the wrong manner. Try this:
window.onload = function () {
$('.replyButton').each(function (index) {
var domElementId = "replyArea" + index;
$('#' + domElementId).on('click', function () {
var replyFieldHtml = '<div class = "span4" id = "replyTextField"><table><tr><td id = "replyPhoto"><img src = "/assets/img/usr/profile_holder.jpg" /></td><td id = "replyContent"><input type = "text" id = "replyInput" onkeydown="if (event.keyCode == 13) wallReply()" placeholder = "leave a reply..." /></td></tr></table></div>';
$(this).html(replyFieldHtml);
console.log(domElementId);
return false;
});
});
}
I ended up using the code below to solve this one, after digging deeper into the history behind .on() and .bind(). Thanks for all your help!
$('a.replyButton').on("click", function(){
var index = $(this).attr('id');
$('#replyArea'+index).html('<div class = "span4" id = "replyTextField"><table><tr><td id = "replyPhoto"><img src = "/assets/img/usr/profile_holder.jpg" /></td><td id = "replyContent"><input type = "text" id = "replyInput" onkeydown="if (event.keyCode == 13) wallReply()" placeholder = "leave a reply..." /></td></tr></table></div>');
});
I ended up changing the "replyLink" ID attribute to just the number. So there were a bunch of /<.a> with class replyButton, and ID attributes as a number. And it seems to do the job nicely, no need to setup the .each() loop too.