show/ hide function in one button (hide_btn) - javascript

I have to program an web-app (Mäxle) for an exam and I am a total beginner.
Hopefully s.o. can help me with that.
index.html (buttons):
<div id="buttons_container" class="container">
<div class="row">
<br>
<button type="button" id="shuffle_btn" class="btn btn-primary">shuffle</button>
<button type="button" id="hide_btn" class="btn btn-success">hide / show</button>
</div>
</div>
function.js:
function test_shuffle () {
var arr = ["11",
"21","22",
"31","32","33","34","35","36",
"41","42","43","44","45","46",
"51","52","53","54","55","56",
"61","62","63","64","65","66"];
var max_index = arr.length -1;
var zufall = Math.floor(Math.random() * max_index) + 1 ;
var final = arr [zufall];
$('#ausgabe_shuffle').html(final);
}
function test_hide () {
$("hide_btn").click(function(){
$("--").hide();
});
}
event.js:
$(document).ready(function() {
$('body').on('click', '#shuffle_btn', function (e) {
test_shuffle ();
});
$('body').on('click', '#hide_btn', function (e) {
$("*").html("--");
test_hide ();
});
});
When I click the hide_btn right now, everthing disappears and this "--" will be displayed. The click works but I want to hide the numbers I got from the array, eg. "32"
Thank you very much in advance

$("*").html("--"); // This overrides all html inside body and prints "--".
You can replace this with
$("#ausgabe_shuffle").toggle(); // This will show or hide your values printed inside #ausgabe_shuffle tag.

Related

Dynamic add button show wrong value jquery

<script type="text/javascript">
var i = 0;
var j = 1;
$("#add").click(function(){
++i;
var c = i + j;
$("#dynamicpre").append('<div class="dynamicfields mb-5"><h5>Track:' + c + '</h5></div>');
});
$(document).on('click', '.remove-tr', function(){
$(this).closest('.dynamicfields').remove();
});
</script>
In the above question I am simply append a value through c variable. Now, What happen here when I click on add button it show Track:2 but when I click on remove and click again on add button then it show Track:3 but I want to show Track:2. So, How can I do this? Please help.
Thank You
From your .remove-tr click code it seems that you will be having .remove-tr element inside .dynamicfields div then only your $(this).closest would work, so I have added .remove-tr button dymanically.
Check comments for explanation.
$("#add").click(function() {
// default track value
let c = 1;
// get last dynamicfields's h5 element inside #dynamicpre
let lastAdded = $("#dynamicpre .dynamicfields h5:last");
// check if there is any dynamicfields is there? if yes then only get track number
if (lastAdded.length) {
// get track number from last dynamicfields from its text
// get track text and replace Track: with empty value and convert it to number
c = 1 + Number(lastAdded.text().replace("Track:", ""));
}
// append new div with remove button
$("#dynamicpre").append('<div class="dynamicfields mb-5"><h5>Track:' + c + '</h5> <input type="button" class="remove-tr" value="remove" /> </div>');
});
$(document).on('click', '.remove-tr', function() {
$(this).closest('.dynamicfields').remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<input type="button" id="add" value="add">
<div id="dynamicpre">
</div>
you have to -1 the value of "j" on removing function and also create a remove button at the end only and remove the last div on remove button click then it will work fine :
var i = 0;
var j = 1;
$("#add").click(function(){
++i;
var c = i + j;
$("#dynamicpre").append('<div class="dynamicfields mb-5"><h5>Track:' + c + '</h5></div>');
});
$(document).on('click', '.remove-tr', function(){
if(j>=1){
i --;
}
$(".dynamicfields:last-child").remove()
});
<input value="add" type="button" id="add" />
<div id="dynamicpre">
hammad
</div>
<input value="remove" type="button" class="remove-tr" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>

How to use multiple IDs in one function

How to use it on multiple ids such that when #more1 is clicked , #details1 will appear. And when #more2 is clicked , #details2 will appear?
Note that I want it only using one function.
Thank U.
$(document).ready(function () {
$('#more1,#more2').click(function () {
$('#details1,#details2').slideToggle();
});
});
You can use a more general selector: $('[id^="more"]').
This will select all items that have an id that starts with "more", and will have a click event tied to them.
Then you can use the number in the id property and use it to build the id of the target.
$('[id^="more"]').click(function()
{
let id = $(this).attr('id');
let num = /\d+/.exec(id)[0];
$('#details' + num).slideToggle();
});
$(document).ready(function()
{
$('[id^="more"]').click(function()
{
let id = $(this).attr('id');
let num = /\d+/.exec(id)[0];
$('#details' + num).slideToggle();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<button id="more1">One</button>
<span id="details1">Each Section</span>
</div>
<div>
<button id="more2">Two</button>
<span id="details2">Is Independent</span>
</div>
<div>...</div>
<div>
<button id="more25">Twenty Five</button>
<span id="details25">Of all the others</span>
</div>
You can check the id of the current item and act accordingly:
if($(this).attr('id') == 'more1') $('#details1').slideToggle();
A more elegant solution would be:
$('#details' + $(this).attr('id')[$(this).attr('id').length - 1]).slideToggle();
The last one uses the fact that the numbering in the ids is similar, and if you have less than 10 such ids it will work properly.
You can use for loop
$(document).ready(function()
{
var length = 9; // any number you need
for (var i = 0; i < length; i++ ) {
$('#more' + i).click(function()
{
$('#details' + i).slideToggle();
});
}
});

How to add working dropify inputs dynamically

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.

Set HTML div value using JavaScript

I have an HTML page with 2 divs (among other things) - "person" and "person-success", in which "person" is visible and "person-success" hidden. When a button in "person" is clicked, the visible div hides and the previously-hidden div "person-success" shows. The code is given below:
<div id="person">
<br><br>
<div id="counterNum" class="counter-color" l10nID="M_AC_UT_TXT_20"></div>
<div role="form">
...
<button type="submit" id="addPerson" class="btn btn-success" l10nID="M_LG_BTN_1"></button>
</div>
</div>
<div id="person-success" class="hide">
...
<p>
<span l10nID='M_AC_UT_TXT_19'></span>
You can add <span id="limit"></span> more people. <a href='<?php echo $root; ?>edituseraccount.php?action=addPerson'>Add another person?</a>
</p>
</div>
The JavaScript:
$('#addPerson').click(function() {
var counter = 0;
var limit = 10;
var args = {
...
$.post("addperson.php",args,function(data){
var response = JSON.parse(data);
if(response.status == 0){
counter += 1;
if (counter < limit){
$('#counterNum').text(counter);
$('#person').hide();
$('#limit').text(limit-counter);
$('#person-success').show();
}
}
console.log(data);
});
});
Now, when the button is pressed, while "person-success" will show, clicking on "Add another person?" should show "person" and hide "person-success" again. Only this time, the div "counterNum" should be updated with the value of "counter" from the JavaScript. With my code, clicking the link reopens the "person" div and hides the other, but counterNum is not updated, or even shown. Does anyone know how I could do that?
I hope I could explain my problem. Would be grateful for any help!!
Var counter Make it as global. Because each time when you click on the addPerson button when counter resets to zero.
var counter = 0;
var limit = 10;
$('#addPerson').click(function() {
var args = {
...
$.post("addperson.php",args,function(data){
var response = JSON.parse(data);
if(response.status == 0){
counter += 1;
if (counter < limit){
$('#counterNum').text(counter);
$('#person').hide();
$('#limit').text(limit-counter);
$('#person-success').show();
}
}
console.log(data);
});
});
The variable you declare is local scope.
Declare variable globally outside the click event called.
On each click it resets counter to 0.
Hope it helps !!!

How to add array items to <li> Jquery

I'm working on something really simple, a short quiz, and I am trying to make the items I have listed in a 2-d array each display as a <li>. I tried using the JS array.join() method but it didn't really do what I wanted. I'd like to place them into a list, and then add a radio button for each one.
I have taken the tiny little leap to Jquery, so alot of this is my unfamiliarity with the "syntax". I skimmed over something on their API, $.each...? I'm sure this works like the for statement, I just can't get it to work without crashing everything I've got.
Here's the HTML pretty interesting stuff.
<div id="main_">
<div class="facts_div">
<ul>
</ul>
</div>
<form>
<input id="x" type="button" class="myBtn" value="Press Me">
</form>
</div>
And, here is some extremely complex code. Hold on to your hats...
$(document).ready (function () {
var array = [["Fee","Fi","Fo"],
["La","Dee","Da"]];
var q = ["<li>Fee-ing?","La-ing?</li>"];
var counter = 0;
$('.myBtn').on('click', function () {
$('#main_ .facts_div').text(q[counter]);
$('.facts_div ul').append('<input type= "radio">'
+ array[counter]);
counter++;
if (counter > q.length) {
$('#main_ .facts_div').text('You are done with the quiz.');
$('.myBtn').hide();
}
});
});
Try
<div id="main_">
<div class="facts_div"> <span class="question"></span>
<ul></ul>
</div>
<form>
<input id="x" type="button" class="myBtn" value="Press Me" />
</form>
</div>
and
jQuery(function ($) {
//
var array = [
["Fee", "Fi", "Fo"],
["La", "Dee", "Da"]
];
var q = ["Fee-ing?", "La-ing?"];
var counter = 0;
//cache all the possible values since they are requested multiple times
var $facts = $('#main_ .facts_div'),
$question = $facts.find('.question'),
$ul = $facts.find('ul'),
$btn = $('.myBtn');
$btn.on('click', function () {
//display the question details only of it is available
if (counter < q.length) {
$question.text(q[counter]);
//create a single string containing all the anwers for the given question - look at the documentation for jQuery.map for details
var ansstring = $.map(array[counter], function (value) {
return '<li><input type="radio" name="ans"/>' + value + '</li>'
}).join('');
$ul.html(ansstring);
counter++;
} else {
$facts.text('You are done with the quiz.');
$(this).hide();
}
});
//
});
Demo: Fiddle
You can use $.each to iterate over array[counter] and create li elements for your options:
var list = $('.facts_div ul');
$.each(array[counter], function() {
$('<li></li>').html('<input type="radio" /> ' + this).appendTo(list);
}
The first parameter is your array and the second one is an anonymous function to do your action, in which this will hold the current element value.
Also, if you do this:
$('#main_ .facts_div').text(q[counter]);
You will be replacing the contents of your element with q[counter], losing your ul tag inside it. In this case, you could use the prepend method instead of text to add this text to the start of your tag, or create a new element just for holding this piece of text.

Categories

Resources