I have written code to upload multiple files by cloning input field in jquery.
Here the logic is; if #file_1 field is empty, the $('#addBtn').on('click', function () is supposed to go in else part of if condition and display the relevant hidden <p> tag. If first field is left empty, the add button (add more button) should not clone the field. Instead it should show a message to user to upload file in the first available field first and the click add button to upload more file. Here Jquery show()/hide function is not working.
Please have a look on my code, I'll be much obliged. Thank you!
console.log('objection page here');
var Index = 1;
// START CODE FOR BASIC DATA TABLE
$(document).ready(function () {
$('#addBtn').on('click', function () {
var uploadFieldVal = $('#file_'+ Index).val();
console.log(uploadFieldVal);
if(uploadFieldVal !="")
{
Index++;
var uFile = $('#file_1').clone();
//var id = "btnAdd_" + Index;
var fileItem = "<input type='file' name='fileUpload[file][]'' id='file_" + Index + "'class='form-control'/> ; " +
"<p id='fileMsg_" + Index + "style='visibility: hidden; color: red'>Please attach file here first </p>;"
$('#fileDiv').append(fileItem);
}
else
{
console.log('fileMsg_'+Index);
$('#fileMsg_'+Index).show();
//$('#fileMsg_1).show(); //its also not working
}
});
});
<button class="btn btn-sm btn-primary float-right" id="addBtn" type="button"><i class="fa fa-plus"></i>
</button>
<div class="form-group" id="fileDiv">
<label for="file_1">File</label>
<input type="file" name="fileUpload[file][]" id="file_1" class="form-control"/>
<p id="fileMsg_1" style="visibility: hidden; color: red">Please attach file here first </p>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
.show() does not work on CSS for visibility.
The matched elements will be revealed immediately, with no animation. This is roughly equivalent to calling .css( "display", "block" ), except that the display property is restored to whatever it was initially. If an element has a display value of inline, then is hidden and shown, it will once again be displayed inline.
$(function() {
console.log('objection page here');
var Index = 1;
$('#addBtn').on('click', function() {
var uploadFieldVal = $('#file_' + Index).val();
console.log(uploadFieldVal);
if (uploadFieldVal != "") {
Index++;
var uFile = $('#file_1').clone();
var fileItem = "<input type='file' name='fileUpload[file][]'' id='file_" + Index + "' class='form-control'/> ; ";
fileItem += "<p id='fileMsg_" + Index + "' style='visibility: hidden; color: red'>Please attach file here first </p>;"
$('#fileDiv').append(fileItem);
} else {
console.log('fileMsg_' + Index);
$('#fileMsg_' + Index).css("visibility", "visible");
}
});
});
<button class="btn btn-sm btn-primary float-right" id="addBtn" type="button"><i class="fa fa-plus"></i></button>
<div class="form-group" id="fileDiv">
<label for="file_1">File</label>
<input type="file" name="fileUpload[file][]" id="file_1" class="form-control" />
<p id="fileMsg_1" style="visibility: hidden; color: red">Please attach file here first </p>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
You need to change visibility to visible to "show" it.
See More: https://api.jquery.com/show/
Related
I have a div with id="add-dependent" including 2 rows and a button (add dependent) inside of the div. When "add dependent" button is clicked, the first row would be cloned and insert before (add dependent) button. Actually I have another button outside of the div called (add applicant) and by clicking it, whole of the div would be cloned and added before (add applicant) button. my code is like this :
let nextLabel=2
let nextId=1
function addApplicant(){
var elem= document.querySelector("#add-dependent");
var clone=elem.cloneNode(true);
var add= document.getElementById("add-applicant");
clone.id = "add-dependent"+nextLabel;
elem.parentElement.insertBefore(clone,add);
var label = clone.querySelector("label");
label.innerHTML = '<button class="close remove" onClick="$(this).parent().parent().parent().parent().remove()">x</button>' + "Applicant " + (nextLabel++) ;
}
function addDependent(){
var elem= document.querySelector(".dependent");
var clone=elem.cloneNode(true);
var add= document.getElementById("dependent");
elem.parentElement.insertBefore(clone,add);
var label=clone.querySelector('label');
label.innerHTML= '<button id="btn" name="btn" type="button" class="close float-left" style="font-size:12px;" onClick="$(this).parent().parent().parent().remove();" >x</button>';
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="add-dependent">
<div class="form-row dependents">
<div>
<label class="text-left" contenteditable="true">Applicant 1: </label>
</div>
<div >
<input type="number" placeholder="age">
</div>
</div>
<div class="form-row dependent">
<div>
<button id="btn" name="btn" type="button" class="close " onClick="$(this).parent().parent().remove();" >x</button>
</div>
<div>
<input type="number" placeholder="age">
</div>
</div>
<button id="dependent" onClick="addDependent()">Add dependent</button>
</div>
<button id="add-applicant" onClick="addApplicant()">Add applicant</button>
my problem is when i click on (add dependent) in cloned div, the row is added to main div not cloned one.
hope to here you soon.
Thanks a lot
There are many changes I made to your code and I'll try to explain them here. When you're working with duplicating, appending, removing etc, id's can become difficult to work with - you can't have duplicates of IDs and your code then has to track which id is affected by which button etc.
Its much easier to work with relative paths. For instance when you want to add a dependent, it's easier to say 'find a dependent input to clone and place it inside the container from where I clicked this add-dependent button' - and walla no need for ids. To find the relative div's, I used a combination of event.target, closest() and querySelctor - like this:
e.target
.closest('.add-applicant-container')
.querySelector('.dependents')
.append(clone);
This says Starting from the button I clicked, find the closest '.add-applicant-container' and inside that find the first '.dependents' and place our clone right after that
Finally, the buttons. Because you're creating and destroying these buttons in the process, it's best to set up a listener on document and test to see which button was clicked. This is called event delegation. For the dependent delete button, we only need to find the relative element and delete it so:
if (e.target.classList.contains('close')) {
e.target.closest('.dependent-container').remove()
}
let nextLabel = 2
let nextId = 1
document.addEventListener('click', function(e) {
if (e.target.classList.contains('add-applicant')) {
addApplicant(e)
} else if (e.target.classList.contains('btn-dependent')) {
addDependent(e)
} else if (e.target.classList.contains('remove-applicant')) {
e.target.closest('.add-applicant-container').remove()
} else if (e.target.classList.contains('close')) {
e.target.closest('.dependent-container').remove()
}
})
function addApplicant(e) {
let applicant = document.querySelector('.add-applicant-container')
var clone = applicant.cloneNode(true);
clone.id = "add-dependent" + nextLabel;
clone.querySelectorAll('.dependent-container').forEach((el, i) => {
if (i !== 0) el.remove()
})
applicant.parentElement.insertBefore(clone, e.target);
var label = clone.querySelector("label");
label.innerHTML = '<button class="close remove-applicant">x</button>' + "Applicant " + (nextLabel++);
}
function addDependent(e) {
let dependent = document.querySelector('.dependent-container')
var clone = dependent.cloneNode(true);
e.target.closest('.add-applicant-container').querySelector('.dependents').append(clone);
// var label = clone.querySelector('label');
// label.innerHTML = '<button id="btn" name="btn" type="button" class="close float-left" style="font-size:12px;" >x</button>';
}
.add-applicant-container{
padding:10px;
}
.dependent-container{
padding:5px 0 ;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="add-applicant-container">
<div class="form-row dependents">
<div>
<label class="text-left" contenteditable="true">Applicant 1: </label>
</div>
<div>
<input type="number" placeholder="applicant age">
</div>
</div>
<div class="form-row dependent-container">
<div>
<input type="number" placeholder="dependent age"> <button id="btn" name="btn" type="button" class="close ">x</button>
</div>
</div>
<button class="btn-dependent">Add dependent</button>
</div>
<button class="add-applicant">Add applicant</button>
I have this code that enables the users to add a list of keywords to a text area and than submit it. The list will show on a div, then the user has to select one or many words in one line to add it to id="out".
The code is working as of now, but it's not what I want and I'm blocked. What I want is that the user can click (instead of select) one or many words to underline them and then click on the image to add them as a line to id="out".
I've big trouble to solve this as my JS knowledge is very limited, but I hope to learn quickly by working on similar projects and I've a lot in mind.
Thank you
Code:
var arraySearchTerms = [];
function add() {
arraySearchTerms = document.getElementById("searchTerms").value.split('\n');
let newKeywordHtmlStr = '';
for (var i = 0; i < arraySearchTerms.length; i++) {
newKeywordHtmlStr += '<div style="padding: 6px;border-bottom: #b5aeae; border-bottom-style: solid;border-bottom-width: 1px;"><span id="term' + i + '">' + arraySearchTerms[i] + "</span><span style='float: right;'><img src='Red_Cross.png' height='15' width='11'/></span></div>";
}
document.getElementById("keywords").innerHTML += newKeywordHtmlStr;
}
function get_selection() {
var txt = '';
if (window.getSelection) {
txt = window.getSelection().toString();
} else if (document.selection) {
txt = document.selection.createRange().keywords;
}
document.getElementById("out").innerHTML += txt;
}
<TITLE>Test</TITLE>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="negative.css">
<div id="container">
<div id="container2">
Add your search terms:
<textarea type="text" id="searchTerms">
</textarea> <br />
<button onclick="add()">Add >></button><br />
<br /><br /> Negative keywords:
<textarea type="text" id="out"></textarea>
</div>
<div id="container1">
Search terms:
<div id="keywords" onclick="get_selection()"></div>
</div>
</div>
<script src="negative.js"></script>
Draggable function works on other already created elements, but not on the one i'm creating within a function after submit button.
I've checked if i'm adding an id to 'li' elements and it works, so why can't I drag it?
It works when I use it on whole 'ul' element.
HTML:
<div class="container">
<form>
<input type="text" id="entry">
<button id="entryButton">button</button>
</form>
<ul id="list">
</ul>
</div>
$("#entryButton").click(function(){
event.preventDefault(); //stops refreshing
var query = $("#entry").val();
if (query !== "") {
var registry = "<div id='drag'>" + query + "</div>"
$("#list").append(registry)
$("#entry").val("");
return false; //also stops refreshing
console.log(registry);
}
})
$("#drag").draggable({
axis: "y"
});
You can only use an id once, so I would suggest that you use class for that. Furthermore, you should add the draggable to the element after creation, as Ferhat BAŞ has said.
https://jsfiddle.net/exqn1aoc/2/
$("#entryButton").click(function(){
event.preventDefault(); //stops refreshing
var query = $("#entry").val();
if (query !== "") {
var registry = "<div class='drag'>" + query + "</div>"
$("#list").append(registry);
$('#list').children().last().draggable();
$("#entry").val("");
return false; //also stops refreshing
console.log(registry);
}
});
Just use class instead of id for multi pal created item to drag and put your draggable inside button click.
$("#entryButton").click(function() {
event.preventDefault(); //stops refreshing
var query = $("#entry").val();
if (query !== "") {
var registry = "<div id='drag' class='drag'>" + query + "</div>"
$("#list").append(registry)
$("#entry").val("");
$(".drag").draggable({
axis: "y"
});
return false; //also stops refreshing
console.log(registry);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<div class="container">
<form>
<input type="text" id="entry">
<button id="entryButton">button</button>
</form>
<ul id="list">
</ul>
</div>
First you need to put the draggable() function inside your click function.
Second, do not use id . Duplicate id's are not valid HTML and that's what causing only the first #drag to be draggable. Use class instead
See snippet below
$("#entryButton").click(function() {
event.preventDefault(); //stops refreshing
var query = $("#entry").val();
if (query !== "") {
var registry = "<div class='drag'>" + query + "</div>"
$("#list").append(registry)
$("#entry").val("");
$(".drag").draggable()
return false; //also stops refreshing
console.log(registry);
}
})
.drag {
height: 100px;
width: 100px;
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>
<div class="container">
<form>
<input type="text" id="entry">
<button id="entryButton">button</button>
</form>
<ul id="list">
</ul>
</div>
I have a jquery function that on a click event empties a div, gets some json, and then appends to that cleared div. However, the check boxes I am trying to append to said div are not appearing. Here is my code:
$(function() {
$("#nwCol").click(function() {
$('#adDiv').empty();
$.getJSON('/_adv_detect_su', function(data) {
$(data.advanced).each(function(index, value) {
if (value.present === 'yes') {
$('#adDiv').append("<input name='aoCB' type='checkbox' checked='checked'>" + value.name + "</input>");
} else {
$('#adDiv').append("<input name='aoCB' type='checkbox'>" + value.name + "</input>");
}
});
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="col-md-7 text-center">
<form id="advDet">
<div id="adDiv"></div>
<div id="saveao"> <button id="svAoBtn" type="button" class="btn btn-primary center-block">Save</button> </div>
</form>
</div>
I have this working when not clearing the div, and using the .after function. However, this is not ideal.
If you are using any AD BLOCK Your div ID, starting with 'ad' will get #header_ads style from user agent browser, that set "display: none", so it appears to not work, even if it is working. As you can see here on this print screen http://storage1.static.itmages.com/i/17/0616/h_1497628218_1896684_0db84ac526.png
So I changed your div id to anotherID now it's working
Run the snippet below.
$(function() {
$("#nwCol").click(function() {
var anotherDiv = $('#anotherID');
anotherDiv.empty();
var data = {
advanced: [{present: 'yes', name: 'test1'}, {present: 'no', name: 'test2'}]
};
$(data.advanced).each(function(index, value) {
console.log(value);
if (value.present === 'yes') {
anotherDiv.append("<input name='aoCB' type='checkbox' checked='checked'>" + value.name + "</input>");
} else {
anotherDiv.append("<input name='aoCB' type='checkbox'>" + value.name + "</input>");
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-7 text-center">
<form id="advDet">
<div id="anotherID"></div>
<div id="saveao">
<button id="svAoBtn" type="button" class="btn btn-primary center-block">Save</button>
</div>
</form>
Test Click
</div>
Please see the snippet (looks like your button id selector was incorrect):
$(function() {
$("#svAoBtn").click(function() {
$('#adDiv').empty();
$.getJSON('https://api.myjson.com/bins/16qosb', function(data) {
$(data.advanced).each(function(index, value) {
var checkedInput = "";
if (value.present === 'yes') {
checkedInput = "checked='checked'";
}
$('#adDiv').append("<input name='aoCB' type='checkbox'" + checkedInput + ">" + value.name + "</input>");
});
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-7 text-center">
<form id="advDet">
<div id="adDiv"></div>
<div id="saveao"> <button id="svAoBtn" type="button" class="btn btn-primary center-block">Save</button> </div>
</form>
</div>
thanks in advance.
The question is:
I have 2 buttons that shows the content of the div when the user click on it.
The content of the div are in a function that shows the content when the users click on the button (onclick).
But when the page loads just appear the two buttons without any content, is there any way to 'put' one of these buttons as active by default?
I tried with this:
Html:
<div class="diferencias col-md-12 col-lg-12">
<div class="diferencias col-md-6 col-lg-6"><input type="button" value="Web" onClick="fashioncatweb();">
</div>
<div class="diferencias col-md-6 col-lg-6"> <input type="button" value="Logo" onClick="fashioncatlogo();">
</div>
</div>
<div class="row">
<div id="container">
<div id="content"></div>
</div>
</div>
JS:
function fashioncatweb()
{
var text = "<p>text";
var img = "images/.....";
var content = "<div class=\"col-md-7\"><div class=img><img class=img-responsive src=\"" + img + "\" alt=\"\" /></div></div>"
+ "<div class=\"col-md-5\"><div class=pre-scrollable id=\"fashion\">" + text + "</div></div>";
appendToContainer(content);
}
function fashioncatlogo()
{
var text = "<p>text";
var img = "images/....png";
var content = "<div class=\"col-md-7\"><div class=img><img class=img-responsive src=\"" + img + "\" alt=\"logo\" /></div></div>"
+ "<div class=\"col-md-5\"><div class=pre-scrollable id=\"logo\">" + text + "</div></div>";
appendToContainer(content);
}
$(document).ready(function () {
piramidalweb();
});
But it just works for one section and I have like 15 different sections.
Thanks again!!
You should have a function that is called on the click of the buttons:
Using pure Javascript:
<input type="button" value="Button1" id="btn1" onclick="showContent(this.id)" />
function showContent(id) {
if(id === "btn1") {
// show the content
}
}
Then call immediately at the base of the page within script tags:
showContent("btn1");
That will load the content immediately.
To improve this you would execute this function onload, or in a ready function within jQuery, but hopefully you'll be able to take it from there.