Duplicate the value from the group of radio - javascript

I want to duplicate the text value of the active radio buttom before other div. Radios are divided into groups. In each group is always active, only one. Therefore, a new value from each group should always be one, too. I will add a text value, but I cant to make the removal of the previous value of the group.
$('.views-exposed-widget').find('.form-type-radio').on('click', function(){
var a = $(this).closest('.form-type-radio').find('label[class="option"]').text();
$('.views-widget-sort-by').before('<span>'+a+'</span>');
});
My example: http://jsfiddle.net/e59ogp8a/

You could name them (and thus create a mapping between the radio group and the spans) so you can find them easily
$('.views-exposed-widget').on('change', 'input', function () {
var self = $(this),
name = this.name,
text = self.closest('.form-type-radio').find('label[class="option"]').text(),
target = $('.views-widget-sort-by').find('[data-for="'+ name +'"]'); // find the related span
// check if we found a related span, and if not create it
if (target.length == 0){
target = $('<span data-for="'+name+'"></span>').appendTo('.views-widget-sort-by');
}
// set the text of the span
target.text( text );
});
Demo at http://jsfiddle.net/gaby/5nutt42g/1/
You also had a wrong id on the the first radio (it should be edit-tid-1-4 and not edit-tid-1-2)

You have to remove all the prev siblings of your div element.
$('.views-exposed-widget').find('.form-type-radio').on('click', function(){
var a = $(this).closest('.form-type-radio').find('label[class="option"]').text();
$('.views-widget-sort-by').prevAll().remove();
$('.views-widget-sort-by').before('<span>'+a+'</span>');
});

You can use the group name as span's class name to clear the values of the group after group's button clicked.
Take a look here: http://jsfiddle.net/e59ogp8a/3/
$('.views-exposed-widget').find('.form-type-radio').on('click', function(){
var a = $(this).closest('.form-type-radio').find('label[class="option"]').text();
var groupName= $(this).find('.dls-radio').attr("name");
console.log($('.views-widget-sort-by').prev('.'+groupName).text(''));
$('.views-widget-sort-by').before('<span class="'+groupName+'">'+a+'</span>');
});

Related

Javascript- Creating To Do list not working

I deleted the button part in my script but not even the first part of my function is working where I type in input box and suppose to be added to the ...I don't understand why. When I run the code without the buttons code which is titled " //BUTTON creation " I get no error but no item is being added to the list. So I have two problems Items aren't being added to my list and aren't displaying and also if I include the button part its saying an error "list.appendChild is not a function"
<input type="text" placeholder="Enter an Activity" id="textItem">
<img src="images/add-button.png" id="addButton">
<div id="container">
<ul class="ToDo">
<!--
<li>
This is an item
<div id="buttons">
<button ></button>
<img src="images/remove-icon.png"id="remove">
<button id="complete"></button>
<img src="images/complete-icon.jpg" id="complete">
</div>
</li>
!-->
</ul>
</div>
<script type="text/javascript">
//Remove and complete icons
var remove = document.createElement('img').src =
"images/remove-icon.png";
var complete = document.createElement('img').src = "images/complete-icon.jpg";
//user clicks add button
//if there is text in the item field we grab the item into var text
document.getElementById("addButton").onclick = function()
{
//value item is the text entered by user
var value = document.getElementById("textItem").value;
//checks if there is a value typed
if(value)
{
addItem(value);
}
//adds a new item to the ToDo list
function addItem(text)
{
var list = document.getElementsByClassName("ToDo");
//created a varibale called item that will create a list item everytime this function is called
var item = document.createElement("li");
//this will add to the innerText of the <li> text
item.innerText = text;
//BUTTON creation
var buttons = document.createElement('div');
buttons.classList.add('buttons');
var remove = document.createElement('buttons');
buttons.classList.add('remove');
remove.innerHTML = remove;
var complete = document.createElement('buttons');
buttons.classList.add('complete');
complete.innerHTML = complete;
buttons.appendChild(remove);
buttons.appendChild(complete);
list.appendChild(buttons);
list.appendChild(item);
}
}
</script>
The problem is in the line:
var list = document.getElementsByClassName("ToDo");
list.appendChild(item);
The line var list = document.getElementsByClassName("ToDo"); will provide a collection, notice the plural name in the api.
You need to access it using :
list[0].appendChild(item);
There are other problems too in the code but hopefully this gets you going!
There are a couple of issues in your code that need to be addressed to get it to work properly.
1) You are creating your image elements and then setting the variables to the src name of that image and not the image object itself. When you use that reference later on, you are only getting the image url and not the element itself. Change var remove = document.createElement('img').src = "images/remove-icon.png" to this:
var removeImg = document.createElement('img')
removeImg.src = "images/remove-icon.png";
2) As #Pankaj Shukla noted, inside the onclick function, getElementsByClassName returns an array, you will need to address the first item of this array to add your elements. Change var list = document.getElementsByClassName("ToDo") to this:
var list = document.getElementsByClassName("ToDo")[0];
3) For your buttons, you are trying to creating them using: var remove = document.createElement('buttons'). This is invalid, buttons is an not the correct element name, its button. Additionally, you are re-declaring the variables remove and complete as button objects, so within the onclick function it reference these buttons, not the images you defined earlier. So when you assign the innerHTML to remove and complete, you are assigning the buttons innerHTML to itself. The solution is to change the image variables to something different.
4) Finally, also relating to the buttons, you are assigning the innnerHTML to an image object, that's incorrect. You can either insert the html text of the img directly, or append the image object as a child of the button, similar to how the button is a child of the div.
The updated code with all these changes looks like this:
//Remove and complete icons
var removeImg = document.createElement('img');
removeImg.src = "images/remove-icon.png";
var completeImg = document.createElement('img');
completeImg.src = "images/complete-icon.jpg";
//user clicks add button
//if there is text in the item field we grab the item into var text
document.getElementById("addButton").onclick = function() {
//value item is the text entered by user
var value = document.getElementById("textItem").value;
//checks if there is a value typed
if (value) {
addItem(value);
}
//adds a new item to the ToDo list
function addItem(text) {
var list = document.getElementsByClassName("ToDo")[0];
//created a varibale called item that will create a list item everytime this function is called
var item = document.createElement("li");
//this will add to the innerText of the <li> text
item.innerText = text;
//BUTTON creation
var buttons = document.createElement('div');
buttons.classList.add('buttons');
var remove = document.createElement('button');
remove.classList.add('remove');
remove.appendChild(removeImg);
var complete = document.createElement('button');
complete.classList.add('complete');
complete.appendChild(completeImg);
buttons.appendChild(remove);
buttons.appendChild(complete);
list.appendChild(buttons);
list.appendChild(item);
}
}

Form values are overwritten after change

I have a form that shows up when each row in a table is double clicked. The values of this form can be updated and the form should be submitted with all row changes. But each time I double click on a row and edit the values of that form for that row, the previous values I had changed get overwritten. In order to work around this, I tried adding all the changes to a map with the row id as the key and the values of the form as the value. But the form still won't update with the new values. Here is a fiddle to demonstrate what I mean:
https://jsfiddle.net/4fr3edk7/2/
If I double click on the row that says "Adam Smith" and change that name to John Doe, when I double click on the second row and then double Click on "Adam Smith" again, it should say "John" on the first textbox and "Doe" on the second one. But the new value never seems to save.
This code snippet loops through each key, then loops through each value of that key:
for(var i = 0; i<key.length; i++){
var getval = globalchanges[key[i]];
for(var k=0; k<getval.length; k++){
$("#input1").val(getval[0]);
$("#input2").val(getval[1]);
}
}
How can I get the new changes to save? (The table rows don't have to show the changes, just the textbox values). Any help would be appreciated.
First, as mentioned by #Taplar you are binding the click event multiple times. Your approach is close enough, the idea of storing the changes is valid. You should have 2 functions, store the changes on button click and the second one to retrieve the changes by id.
Updated Fiddle
This function will get the values of the form and will store in on a global object
function setMap(id){
var firstrow = $("#input1").val();
var secondrow = $("#input2").val();
globalchanges[id] = [firstrow,secondrow];
}
This other function will check if the global object has values for the passed id, if not, it will use the values on the row
function getMap(id, tr){
if(globalchanges[id] != undefined && globalchanges[id].length == 2){
$("#input1").val(globalchanges[id][0]);
$("#input2").val(globalchanges[id][1]);
}
else{
$("#input1").val($(tr).find('td').eq(1).text());
$("#input2").val($(tr).find('td').eq(2).text());
}
}
Please note there are also changes on the dbclick and click events, they should be separated
$("#table tr").dblclick(function(){
$("#txtbox-wrapper").css({"display" : "block"});
var id = $(this).find('td').eq(0).text();
$('#id').val(id);
getMap(id,this);
});
$("#savebtn").click(function(){
var id = $('#id').val();
setMap(id);
});
And that we added and additional input to store the id on the form.
You are going to need to rethink your logic because of this part
$("#table tr").dblclick(function(){
$("#txtbox-wrapper").css({"display" : "block"});
var id = $(this).find('td').eq(0).text();
$("#input1").val($(this).find('td').eq(1).text());
$("#input2").val($(this).find('td').eq(2).text());
$("#savebtn").click(function(){
addToMap(id);
});
});
-Every time- you double click a table row you are adding a new click binding to the savebtn element. This means if you double click both rows, when you click that button it will execute addToMap for both ids. You may have other issues with your logic relying on only two other inputs for multiple rows, but this double/triple/+ binding is going to bite you.
There are few changes required in your logic as well as implementation.
1: Do not bind save event inside row click.
2: You are selecting the value in row double click event from td element. You need to update this element to keep your logic working
3: Keep track of which row is getting updated.
Updated Code
var globalchanges = {};
var rowSelected = null;
$("#table tr").dblclick(function() {
$("#txtbox-wrapper").css({
"display": "block"
});
rowSelected = $(this).find('td').eq(0).text();
$("#input1").val($(this).find('td').eq(1).text());
$("#input2").val($(this).find('td').eq(2).text());
});
$("#savebtn").click(function() {
addToMap(rowSelected);
});
function addToMap(row) {
var array = [];
var changes = {};
var firstrow = $("#input1").val();
var secondrow = $("#input2").val();
array.push(firstrow, secondrow);
globalchanges[row] = array;
makeChanges(row);
}
function makeChanges(row) {
var key = Object.keys(globalchanges);
console.log(key);
$("#table tr td").each(function(k, v) {
if ($(v).text() == key) {
$(v).next().html(globalchanges[row][0]);
$(v).next().next().html(globalchanges[row][1]);
globalchanges = {};
}
});
}
Working fiddle : https://jsfiddle.net/yudLxsgu/

jQuery clone() input value function

I have created a clone function to clone a selection of elements. I have managed to get the basics of the clone function working. CLICK HERE
I have a bug in this function. When the user types text into the input field, it clones the last inputted text and changes the text value for all cloned items.
$('.add-item').on('click', function() {
var value = $('input').val();
if ($('#items-field').val()) {
$('.list-items p').text(value)
$('.list-items:first').clone().appendTo("#items").addClass('isVisible');
$('input').val('');
event.preventDefault();
}
})
Does anyone know how this problem can be resolved?
Clear the value of inputs after you clone(). You can use the find() method to get all the inputs inside the cloned item.
var c = $('.list-items:first').clone();
c.find("input").val(""); // find all inputs and clear
c.appendTo("#items").addClass('isVisible');
Here is a working jsbin sample
Also, In your code, you are reading the input value and setting it to all the p tags's text. You should be setting it only to the p tag of the cloned div.
$(function(){
$('.add-item').on('click', function(e) {
event.preventDefault();
var value = $('#items-field').val();
if (value!="") {
var c = $('.list-items:first').clone();
c.find("input").val(""); // find all inputs and clear
c.appendTo("#items").addClass('isVisible');
c.find("p").text(value);
}
});
})
Here is a working sample of the complete solution

jquery - find 'label' element by 'for' attribute and reset 'for' attribute to new value

I've searched and have found the following to fetch the label.
var label = $("label").attr("for", id);
my initial attempt was to try a variant:
$('label[for|="'+oldId+'"]').attr('for',newId);
where oldId is the current value and newId is the new value.
I don't get an error, but nothing gets changed.
I also tried just fetching the id of the label so I could find the element by id and change the attribute value, but when I try:
var label = $("label").attr("for", oldId);
var id = label.id;
I get id as undefined.
So, basically I want to:
- find a label element by it's for attribute.
- reset the for attribute to a new value.
The requirement seems a bit odd, but:
So, basically I want to:
find a label element by it's for attribute
var theLabel = $('label[for="' + theValueYouWantToFind + '"]');
reset the for attribute to a new value
theLabel.attr("for", theNewValueYouWantItToHave);
This will associate the label with a different element than it was originally associated with (the one with id matching theNewValueYouWantItToHave).
Live Example This starts out with "click me" connected to the checkbox to the left of it. If you click "switch" it connects it to the checkbox on the right instead:
var currentId = $("label").first().attr("for");
$("input[value=Switch]").on("click", function() {
var newId = currentId === "left" ? "right" : "left";
var label = $('label[for="' + currentId + '"]');
label.attr("for", newId);
currentId = newId;
});
<div>
<input type="checkbox" id="left">
<label for="left">Click me</label>
<input type="checkbox" id="right">
</div>
<input type="button" value="Switch">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
You can try as below:
DEMO HERE
var oldId="#myId";
$('label[for="'+oldId+'"]').attr('for',"#newId");
Now the explanations:
var label = $("label").attr("for", id);
Here you are trying to assign id value to the variable and at the same time you are trying to change it
$('label[for|="'+oldId+'"]').attr('for',newId);
This line you have a syntax error after for you have added | instead of ]
var label = $("label").attr("for", oldId);
var id = label.id;
Again the same problem - assignment and change which does not do anything and label will not have any value thus giving you undefined error
Documentation for JQuery's attr
Before you go much further, why are you wanting to change the "for" attribute and is it going to be processed again after you change it?
attr with one parameter returns the value of the attribute ie: attr("for"). attr with two parameters sets the value of the attribute id: attr("for", newValue).
$("label").attr("for", id);
sets the attribute "for" to the value of id.
$('label[for|="'+oldId+'"]').attr('for',newId);
Jquery selector test site confirms that your selector is good. From what I'm seeing this is correct as long as oldId is the value you are looking for, the attribute should change to newId.
var label = $("label").attr("for", oldId);
var id = label.id;
This will find all "label" and set their attribute of "for" to oldId.
the setting attr is returning jquery, but without researching it, I would be surprised if it was returning the label rather than the contents of the attribute it is setting to "oldId", so this will most likely not do what you want.

Get the all button's id in an array in javascript

In my view file i have two div, in div1 there is some buttons, when i click a button in div1 it goes to div2 and in div2 it does same thing, this time it goes to div1.
Now my question is when there is several buttons in div2, how can i take all the button's id in an array. I want to pass this array in a hidden field of another model.
i tried in following way but it does not working.This is my scripting code.
function movebutton(elem){
var teamMember=[];
if( $(elem).parent().attr("id") == "officers_list" ){
$(elem).detach().appendTo('#add_member');
teamMember.push($(elem).attr("id"));
}
else{
$(elem).detach().appendTo('#officers_list');
teamMember.pop($(elem).attr("id"));
}
$("#TeamTeamMember").val(teamMember);
//console.debug('teamMember=>',teamMember);
}
You can use map function. Code below will return an array of ids.
$("#divId input[type='button']").map(function(index,element) { return element.id; });
Here scope of teamMember is local .so whenever you invoke your function it will create new empty array
Make it global
var teamMember=[];
function movebutton(elem){
if( $(elem).parent().attr("id") == "officers_list" ){
$(elem).detach().appendTo('#add_member');
teamMember.push($(elem).attr("id"));
}
else{
$(elem).detach().appendTo('#officers_list');
teamMember.pop($(elem).attr("id"));
}
$("#TeamTeamMember").val(teamMember);
//console.debug('teamMember=>',teamMember);
}
or You could use $.map() function
var teamMember = $("#add_member").find("button").map(function(){
return this.id;
}).get();
Assuming your 2nd div's id is div2 and your buttons marked up with the input tag, the following should create an array containing all buttons' ids that are in the desired div:
var btns = [];
$('#div2 input[type="button"]').each(function() {//if you are using the <button> markup just use $('div2 button').each(..)
btns.push($(this).attr('id'));
});
Hope this helps.

Categories

Resources