Set a value from a choosen option - javascript

So I made a custom select and I want to set a value into div: valueHolder. I used the same code as for text, but it doesn't work.
I tried to use this code:
$('#adwin-select-category').find('div.valueHolder').val(target.val());
var containerCategory = $('#adwin-select-category .dropContainer');
$('#adwin-select-category').on('click', function(event)
{
var target = $(event.target);
if(target.hasClass('valueHolder') || target.attr('id') === '#adwin-select-category')
{
containerCategory.show();
document.getElementById("adwin-select-category").style.borderColor = "#FFAC0D";
}
else if(target.hasClass('dropOption'))
{
$('#adwin-select-category').find('div.valueHolder').text(target.text());
$('#adwin-select-category').find('div.valueHolder').val(target.val());
containerCategory.hide();
document.getElementById("adwin-select-category").style.borderColor = "#DDD";
showElements();
}
});
#adwin-select-category
{
position: relative;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="adwin-select-category" class="btn">
<div class="valueHolder" value=""></div>
</div>
Example of the options:
option 1
I want to set a value from the example option (value="1") to the valueHolder

Here's how to use data- attributes:
$('#adwin-select-category > div').on('click', function(e) {
var divVal = $(this).data('value');
var divText = $(this).text();
console.log( divVal );
console.log( divText );
});
#adwin-select-category
{
position: relative;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="adwin-select-category" class="btn">
<div class="valueHolder" data-value="1">ONE</div>
<div class="valueHolder" data-value="2">TWO</div>
<div class="valueHolder" data-value="3">THREE</div>
<div class="valueHolder" data-value="4">FOUR</div>
</div>

Related

How can I toggle between two sections while keeping one element visible?

var toggles = document.querySelectorAll("[data-toggle-content-section]");
var sections = document.querySelectorAll(".content-bar__section");
var toggleSections = function(event) {
event.preventDefault();
sections.forEach(function(elem) {
console.log(elem) ;
elem.classList.toggle("active");
});
};
toggles.forEach(function(elem) {
elem.addEventListener("click", toggleSections, ) ;
});
Depending on your HTML you could do something like this:
Note that this is just an example and might have to adjusted to reflect your own markup
var toggles = document.querySelectorAll("[data-toggle-content-section]");
var sections = document.querySelectorAll(".content-bar__section");
var toggleSections = function(event) {
event.preventDefault();
sections.forEach(function(elem) {
elem.classList.remove("active");
});
// get the child element of the just clicked toggle element
event.target.querySelector('.content-bar__section').classList.add("active");
};
toggles.forEach(function(elem) {
elem.addEventListener("click", toggleSections);
});
.content-bar__section{
display: none;
}
.active{
display: block;
}
<div data-toggle-content-section>
Headline 1
<div class="content-bar__section">
Section 1
</div>
</div>
<div data-toggle-content-section>
Headline 2
<div class="content-bar__section">
Section 2
</div>
</div>
<div data-toggle-content-section>
Headline 3
<div class="content-bar__section">
Section 3
</div>
</div>
As you also tagged jQuery here the same solution depending on jQuery:
var $toggles = $("[data-toggle-content-section]");
var $sections = $(".content-bar__section");
$toggles.on('click', function() {
event.preventDefault();
$sections.removeClass('active');
$(this).find('.content-bar__section').addClass('active');
});
.content-bar__section {
display: none;
}
.active {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-toggle-content-section>
Headline 1
<div class="content-bar__section">
Section 1
</div>
</div>
<div data-toggle-content-section>
Headline 2
<div class="content-bar__section">
Section 2
</div>
</div>
<div data-toggle-content-section>
Headline 3
<div class="content-bar__section">
Section 3
</div>
</div>
In the case where you have n areas and you want to only show/activate one at a time, the nearly canonical way to do this is:
function selectOne(e) {
document.querySelectAll(".commonClass").forEach(function(elem) {
//disable element
elem.disabled = true;
});
//enable selected element
document.getElementById(e.target).disabled = false;
}

Why is my text output from next() and prev() toggle incorrect?

When clicking the arrows to change the displayed option, the incorrect options is shown.
The user should be able click on the option menu to toggle it open/cosed and be able to click on a option to select it. Alternatively, the arrows could be used to toggle through the options instead.
This is the problematic code:
<script>
$("#arrow_left_physics").click(function() {
var $selected = $(".left_menu_option_selected").removeClass("left_menu_option_selected");
var divs = $("#left_menu__variant_physics").children();
divs.eq((divs.index($selected) - 1) % divs.length).addClass("left_menu_option_selected");
$("#left_menu_open .button-text").text($($selected).text());
});
$("#arrow_right_physics").click(function() {
var $selected = $(".left_menu_option_selected").removeClass("left_menu_option_selected");
var divs = $selected.parent().children();
divs.eq((divs.index($selected) + 1) % divs.length).addClass("left_menu_option_selected");
$("#left_menu_open .button-text").text($($selected).text());
});
</script>
$("#menu_open").click(function() {
$("#menu").toggle();
});
$(".menu_option").click(function() {
if ($(this).hasClass(".menu_option_selected")) {} else {
$(".menu_option").removeClass("menu_option_selected");
$(this).addClass("menu_option_selected");
$("#menu_open .button_text").text($(this).text());
}
});
$("#arrow_left").click(function() {
var $selected = $(".menu_option_selected").removeClass("menu_option_selected");
var options = $("#menu").children();
options.eq((options.index($selected) - 1) % options.length).addClass("menu_option_selected");
$("#menu_open .button_text").text($($selected).text());
});
$("#arrow_right").click(function() {
var $selected = $(".menu_option_selected").removeClass("menu_option_selected");
var options = $("#menu").children();
options.eq((options.index($selected) + 1) % options.length).addClass("menu_option_selected");
$("#menu_open .button_text").text($($selected).text());
});
.menu_open {
Cursor: pointer;
}
.menu {
display: none;
position: absolute;
border: 1px solid;
}
.menu_option {
Cursor: pointer;
Padding: 5px;
}
.menu_option:hover {
Background-Color: black;
Color: white;
}
.menu_option_selected {
color: green;
Background-color: #00ff0a4d;
}
.menu_option_selected:hover {
color: green;
}
.arrow {
Cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input class="arrow" type="button" id="arrow_left" value="❮" />
<input class="arrow" type="button" id="arrow_right" value="❯" />
</div>
<div>
<button class="menu_open" id="menu_open">
<span class="button_text">option1</span>
</button>
</div>
<div class="menu" id=menu>
<div class="menu_option menu_option_selected">option1</div>
<div class="menu_option">option2</div>
<div class="menu_option">option3</div>
<div class="menu_option">option4</div>
<div class="menu_option">option5</div>
<div class="menu_option">option6</div>
</div>
-It seems that the first click of the arrows isn't working and that the index function is incorrect somewhere.
The problem is this line:
$("#menu_open .button_text").text($($selected).text());
$($selected) is the option that was previously selected, so you're showing the text of the previous option, not the current option. (BTW, there's no need to wrap $selected in $(), since it's already a jQuery object.)
You should use $(".menu_option_selected").text() instead of $($selected).text() to get the current option.
You should also make the initial text of the button option1, so it matches the selected option.
$("#menu_open").click(function() {
$("#menu").toggle();
});
$(".menu_option").click(function() {
if ($(this).hasClass(".menu_option_selected")) {} else {
$(".menu_option").removeClass("menu_option_selected");
$(this).addClass("menu_option_selected");
$("#menu_open .button_text").text($(this).text());
}
});
$("#arrow_left").click(function() {
var $selected = $(".menu_option_selected").removeClass("menu_option_selected");
var options = $("#menu").children();
options.eq((options.index($selected) - 1) % options.length).addClass("menu_option_selected");
$("#menu_open .button_text").text($(".menu_option_selected").text());
});
$("#arrow_right").click(function() {
var $selected = $(".menu_option_selected").removeClass("menu_option_selected");
var options = $("#menu").children();
options.eq((options.index($selected) + 1) % options.length).addClass("menu_option_selected");
$("#menu_open .button_text").text($(".menu_option_selected").text());
});
.menu_open {
Cursor: pointer;
}
.menu {
display: none;
position: absolute;
border: 1px solid;
}
.menu_option {
Cursor: pointer;
Padding: 5px;
}
.menu_option:hover {
Background-Color: black;
Color: white;
}
.menu_option_selected {
color: green;
Background-color: #00ff0a4d;
}
.menu_option_selected:hover {
color: green;
}
.arrow {
Cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input class="arrow" type="button" id="arrow_left" value="❮" />
<input class="arrow" type="button" id="arrow_right" value="❯" />
</div>
<div>
<button class="menu_open" id="menu_open">
<span class="button_text">option1</span>
</button>
</div>
<div class="menu" id=menu>
<div class="menu_option menu_option_selected">option1</div>
<div class="menu_option">option2</div>
<div class="menu_option">option3</div>
<div class="menu_option">option4</div>
<div class="menu_option">option5</div>
<div class="menu_option">option6</div>
</div>
Just another version, refactoring your javascript code with some Arrow functions.
const setButtonText = () => {
$("#menu_open .button_text").text(
$(".menu_option_selected").text()
);
}
const moveSelection = direction => {
var selected = $(".menu_option_selected")
var options = $("#menu").children()
var newIndex;
if (direction == 'right') {
newIndex = (options.index(selected) + 1) % options.length
} else {
newIndex = (options.index(selected) - 1) % options.length
}
selected.removeClass("menu_option_selected")
options.eq(newIndex).addClass("menu_option_selected")
setButtonText()
}
// inizilize menu button_text
setButtonText()
$("#arrow_left").click(() => moveSelection('left'));
$("#arrow_right").click( () => moveSelection('right'));
$("#menu_open").click( () => $("#menu").toggle());
$(".menu_option").click( function() {
$(".menu_option_selected").removeClass("menu_option_selected")
$(this).addClass("menu_option_selected")
setButtonText()
});

Switch classes on click next or back

I'm trying to setup multiple-step form in which the first step is visible by default and rest of the steps are hidden with class "hide". I'd like to switch the class with Next and Back button so only one step is visible at a time. Could you please help with this (Already spent an hour on this)
<div class="steps">
<div class="step1">step1</div>
<div class="step2 hide">step2</div>
<div class="step3 hide">step3</div>
<div class="step4 hide">step4</div>
</div>
<div class="back">Back</div>
<div class="next">Next</div>
$('.next').click(function(){
$('div:not(.hide)').next().removeClass('hide');
$('.hide').prev().removeClass('hide')
})
Try combining the 2 actions into one, like so:
$('.next').click(function(){
$('.steps div:not(.hide)').addClass('hide').next().removeClass('hide');
})
That way, you add the .hide class on your current div and then remove it on the next one.
You can use something similar for the Back button, by replacing .next() with .previous()
$('.next').click(function() {
// find the div that is not hidden
var $current = $('.steps div:not(.hide)');
// only perform logic if there is a proceeding div
if ($current.next().length) {
// show the next div
$current.next().removeClass('hide');
// hide the old current div
$current.addClass('hide')
}
});
$('.back').click(function() {
// find the div that is not hidden
var $current = $('.steps div:not(.hide)');
// only perform logic if there is a preceeding div
if ($current.prev().length) {
// show the previous div
$current.prev().removeClass('hide');
// hide the old current div
$current.addClass('hide')
}
});
.hide { display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="steps">
<div class="step1">step1</div>
<div class="step2 hide">step2</div>
<div class="step3 hide">step3</div>
<div class="step4 hide">step4</div>
</div>
<div class="back">Back</div>
<div class="next">Next</div>
You can add a current step variable to track the currently displayed step and two css for styling and showing your content.
jQuery(function($) {
let currentstep = 1;
let maxsteps = 4;
function showstep(step) {
let step_c = '.step' + step;
for (i = 1; i <= maxsteps; i++) {
var step_selector = '.step' + i;
$(step_selector).removeClass('show');
$(step_selector).addClass('hide');
}
$(step_c).removeClass('hide');
$(step_c).addClass('show');
};
$('.next').click(function() {
currentstep = currentstep + 1;
currentstep = (currentstep % (maxsteps + 1));
if (currentstep == 0) currentstep = 1;
showstep(currentstep);
});
$('.back').click(function() {
currentstep = currentstep - 1;
currentstep = (currentstep % (maxsteps + 1));
if (currentstep == 0) currentstep = 4;
showstep(currentstep);
});
});
.hide {
display: none;
}
.show {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="steps">
<div class="step1 show">step1</div>
<div class="step2 hide">step2</div>
<div class="step3 hide">step3</div>
<div class="step4 hide">step4</div>
</div>
<div class="back">Back</div>
<div class="next">Next</div>
I converted Taplar's answer to a jQuery plugin.
You are essentially navigating left or right by one, using the previous and next functions. These functions navigate through the sibling elements.
(function() {
$.fn.moveRight = function(className) {
var $curr = this.find('div:not(.' + className + ')');
if ($curr.next().length) $curr.next().removeClass(className);
else this.find('div:first-child').removeClass(className);
$curr.addClass(className);
return this;
};
$.fn.moveLeft = function(className) {
var $curr = this.find('div:not(.' + className + ')');
if ($curr.prev().length) $curr.prev().removeClass(className);
else this.find('div:last-child').removeClass(className);
$curr.addClass(className);
return this;
};
})(jQuery);
$('.next').on('click', (e) => $('.steps').moveRight('hide'));
$('.back').on('click', (e) => $('.steps').moveLeft('hide'));
.hide {
display: none;
}
.nav {
width: 260px;
text-align: center;
}
.nav .nav-btn::selection { background: transparent; }
.nav .nav-btn::-moz-selection { background: transparent; }
.nav .nav-btn {
display: inline-block;
cursor: pointer;
}
.steps {
width: 260px;
height: 165px;
border: thin solid black;
text-align: center;
line-height: 165px;
font-size: 3em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="steps">
<div class="step1">step1</div>
<div class="step2 hide">step2</div>
<div class="step3 hide">step3</div>
<div class="step4 hide">step4</div>
</div>
<div class="nav">
<div class="nav-btn back">[ << Back ]</div>
<div class="nav-btn next">[ Next >> ]</div>
</div>

remove class to sibling of elemnt jquery

I have this Jquery function, with a filter that adds a class named selected to the filter by click and shows all that data filter tags of the selected filter.
I want to define that if the sibling of the chosen element has a class named selected, that class needs to be removed from the rest and has to be added to only the selected element.
Function Script
(function ($) {
"use strict";
$.fn.filter = function (options) {
var defaults = {
nav: '[data-filter]' //
}
var $this = this,
settings = $.extend(defaults, options),
$target = $(settings.target),
selected = [];
return this.each( function() {
var $element = $(this);
$(settings.nav).each( function() {
$(this).click( function(event) {
// add selected class
$(this).toggleClass('selected');
// manipulate selected terms array
if ($.inArray($(this).data('filter'), selected) < 0 ) {
selected.push($(this).data('filter'));
} else {
var index = $.inArray($(this).data('filter'), selected);
selected.splice(index, 1);
}
// show/hide elements
$element.find('[data-filter-tags]').each( function() {
var terms = $(this).data('filter-tags').split(','),
show = null;
for (var i=0;i<selected.length;i++) {
show = ($.inArray(selected[i], terms) >= 0 && show !== false);
}
if (show || selected.length == 0) {
$(this).fadeIn();
} else {
$(this).fadeOut();
}
});
event.preventDefault();
});
});
});
};
}(jQuery));
HTML
<div id="tags">
<div id="cities" data-activeclass="selected">
תל אביב
רמת גן
הכל
<div>
</br>
משרה מלאה
משרה חלקית
הכל
</br>
מזכירות
הפעלה
הכל
</br>
</nav>
<div id="filter">
<div class="block" style="background: green" data-filter-
tags="time,kind,city,telaviv,full,sec">תל אביב משרה מלאה מזכירות</div>
<div class="block" style="background: blue" data-filter-
tags="time,kind,city,ramatgan,full,sec">רמת גן מלאה מזכירות</div>
<div class="block" style="background: blue" data-filter-
tags="time,kind,city,ramatgan,part,op">רמת גן חלקית הפעלה</div>
<div class="block" style="background: blue" data-filter-
tags="time,kind,city,telaviv,full,op">תל אביב מלאה הפעלה</div>
<div class="block" style="background: blue" data-filter-
tags="time,kind,city,ramatgan,part,sec">רמת גן חלקית מזכירות</div>
</div>
I want to define that if the sibling of the choosen elemnts has class named
"selected" remove the class from them and add it only to the selected element.
If clicking the element selects it and deselects all of its siblings, then in your click handler:
$(this).addClass("selected").siblings().removeClass("selected");
Simplified live example:
$("[data-filter]").on("click", function() {
$(this).addClass("selected").siblings().removeClass("selected");
});
[data-filter] {
border: 1px solid blue;
}
.selected {
background-color: yellow;
}
<div>
<span data-filter="1">one</span>
<span data-filter="2">two</span>
<span data-filter="3">three</span>
<span data-filter="4">four</span>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
If clicking the element toggles it, we want toggleClass (which you have) but the rest is the same:
$(this).toggleClass("selected").siblings().removeClass("selected");
...since the .siblings().removeClass("selected"); part just won't do anything if the current element was the one that was selected.
Simplified live example:
$("[data-filter]").on("click", function() {
$(this).toggleClass("selected").siblings().removeClass("selected");
});
[data-filter] {
border: 1px solid blue;
}
.selected {
background-color: yellow;
}
<div>
<span data-filter="1">one</span>
<span data-filter="2">two</span>
<span data-filter="3">three</span>
<span data-filter="4">four</span>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

how to delete a particular element in javascript

I want to make a function to create a new box when I click 'add new box' button and after that, it will also able to delete the box when I click the particular delete button which is related with the box. How to make the function in javascript? Should I save in an array for every new element that it creates?
My code:
function addBox() {
var el = document.getElementById('target');
var clone = el.cloneNode(true);
var frame = document.getElementById('container');
var attr = document.createAttribute('val');
attr.value = 'demo';
el.setAttributeNode(attr);
frame.appendChild(clone);
}
<div id="container">
<div id="target" class="foo" val="demo">
<div class="content" style="width:100px;height:100px;background:orange;margin:1px" ></div>
</div>
</div>
<button onclick="addBox();">Add box</button>
<button onclick="deleteBox();">Delete box</button>
I wanted to be like this!
You need to target the button element using this as an argument on the deleteBox() function and then the parent of the button by using parentNode and then apply remove() method on it:
function addBox() {
var el = document.getElementById('target');
var clone = el.cloneNode(true);
var frame = document.getElementById('container');
var attr = document.createAttribute('val');
attr.value = 'demo';
el.setAttributeNode(attr);
frame.appendChild(clone);
}
function deleteBox(e){
e.parentNode.remove()
}
.content{
width: 100px;
height: 100px;
margin-bottom: 10px;
background: #F5A623;
display: inline-block;
vertical-align: middle;
}
<div id="container">
<div id="target" class="foo" val="demo">
<div class="content" style="width:100px;height:100px;background:orange;margin:1px"></div>
<button onclick="deleteBox(this);">Delete</button>
</div>
</div>
<button onclick="addBox();">Add box</button>
As a sidenote, I strongly recommend you to have unique ids on elements.
Try this,
<div id="container">
<div id="target" class="foo" val="demo">
<div class="content">aaa</div>
<button onclick="deleteBox(this);">Delete box</button>
</div>
</div>
<button onclick="addBox();">Add box</button>
function addBox() {
var el = document.getElementById('target');
var clone = el.cloneNode(true);
var frame = document.getElementById('container');
var attr = document.createAttribute('val');
attr.value = 'demo';
el.setAttributeNode(attr);
frame.appendChild(clone);
}
function deleteBox(obj){
obj.parentElement.remove();
}
JQuery:
function deleteBox(){
$( "#target" ).remove();
}
Javascript:
function deleteBox(){
document.getElementById('target').remove()
}
This is alternative example, You can try in your code :)
var sentenceIndex = 1;
function addSentence() {
var n = sentenceIndex;
var html = '<div class="form-item-wrap" id="sentencebox' + n + '">'+
'<div class="form-item">'+
'<input class="form-control" type="text" id="sentence'+n+'" name="sentence[' + n + ']">'+
'</div>'+
'<div class="course-region-tool">'+
'<a href="javascript:void(0);" onclick="removeSentence('+n+');" class="delete" title="delete">'+
'<i class="icon md-recycle"></i></a></div></div>';
$("#addSentenceDiv").append(html);
sentenceIndex = sentenceIndex + 1;
}
function removeSentence(id) {
console.log(id);
$("#sentencebox"+id).remove();
}

Categories