I have an app where when the user clicks on a table, assigned to btnAlternativeService, the content from this table swaps with another one.
The jQuery I have used involves creating two variables for each piece of content in the table, one to act as a JS selector and another to retain the original content. It looks like this:
// Switch between the two services
btnAlternativeService.on('click', function(){
// Set original recommended text variables
var serviceSubTextOriginal = $('.js-second-step .subtext-top').text();
var serviceProductTitleOriginal = $('.js-second-step .product-title').text();
var serviceMileageOriginal = $('.js-miles').text();
var serviceRecommendationOriginal = $('.js-second-step .full-rec').text();
// Set recommended text selector variables
var serviceSubText = $('.js-second-step .subtext-top');
var serviceProductTitle = $('.js-second-step .product-title');
var serviceMileage = $('.js-miles');
var serviceRecommendation = $('.js-second-step .full-rec');
// Set original alternative variables
var alternativeProductTitleOriginal = $('.js-alternative h3').text();
var alterativeMilageOriginal = $('.js-miles-alternative').text();
var alternativeSubTextOriginal = $('.js-alternative .alternative-subtext').text();
// Set alternative selector variables
var alternativeProductTitle = $('.js-alternative h3');
var alterativeMilage = $('.js-miles-alternative');
var alternativeSubText = $('.js-alternative .alternative-subtext');
// Swap everything around
serviceProductTitle.text(alternativeProductTitleOriginal);
serviceMileage.text(alterativeMilageOriginal);
serviceRecommendation.text(alternativeSubTextOriginal);
alternativeSubText.text(serviceRecommendationOriginal);
alternativeProductTitle.text(serviceProductTitleOriginal);
alterativeMilage.text(serviceMileageOriginal);
});
This seems very long winded - is there a better way for me to swap the content around?
You can select the elements by order and create 2 collections and use the indices for setting the text contents:
var $first = $('.js-second-step .subtext-top, ...');
var $second = $('.js-alternative h3, ...');
$first.text(function(index, thisText) {
// select the corresponding element from the second set
var $that = $second.eq( index ), thatText = $that.text();
$that.text( thisText );
return thatText;
});
Use a function:
function switchContent(selector_1, selector_2){
data_1 = $(selector_1).text()
data_2 = $(selector_1).text()
$(selector_1).text(data_2)
$(selector_2).text(data_1)
}
btnAlternativeService.on('click', function(){
switchContent('.js-alternative h3', '.js-second-step .product-title')
switchContent('.js-miles-alternative', '.js-miles')
switchContent('.js-alternative .alternative-subtext', '.js-second-step .full-rec')
});
Related
I have successfully created a button which adds text to the webpage however I do not know a viable way to remove text once this has been created. The js code I have is:
var addButtons = document.querySelectorAll('.add button');
function addText () {
var self = this;
var weekParent = self.parentNode.parentNode;
var textarea = self.parentNode.querySelector('textarea');
var value = textarea.value;
var item = document.createElement("p");
var text = document.createTextNode(value);
item.appendChild(text)
weekParent.appendChild(item);
}
function removeText() {
//document.getElementbyId(-).removeChild(-);
}
for (i = 0; i < addButtons.length; i++) {
var self = addButtons[i];
self.addEventListener("click", addText);
}
I have viewed various sources of help online including from this site however I simply cannot get any to work correctly. Thank you in advance.
Sure, it should be easy to locate the added <p> tag relative to the remove button that gets clicked.
function removeText() {
var weekParent = this.parentNode.parentNode;
var item = weekParent.querySelector("p");
weekParent.removeChild(item);
}
If there is more than 1 <p> tag inside the weekParent you will need a more specific querySelector.
I have a dilemma when I try to target a particular element through accessing child nodes click event will not work but if I use getElementById then attach it through that it will work butI need to ideally do it through child nodes. below is my code.
jQuery('#begin_consult').click(function(){
jQuery('.cq-container').show();
jQuery('#begin_consult').hide();
if(jQuery('.option').hasClass('c_questions')){
var y = document.getElementsByClassName('c_questions');
for(var i = 0; i < y.length; i++){
jQuery('.main-body').append(y[i].innerHTML);
var get_age_gparent = document.getElementsByClassName('age-check')[0];
get_age_gparent.style = "display:block;";
var get_age_parent = get_age_gparent.childNodes[1];
var getOptionsDD = get_age_parent.childNodes[3];
var getOptionsUL = getOptionsDD.childNodes[1];
var getInputNo = getOptionsUL.childNodes[1];
var getRadioBtnAge = getInputNo.childNodes[0];
getRadioBtnAge.onclick = function(){
alert('fffff');
};
}
}
});
I suggest you use another approach. Your current implementation makes your code strictly dependent on the structure of your HTML. If you ever change even the slightest item, it will break. you add an image, an icon, or wrap an element in a div.
If i was you, i would reference them in a different manner.
Sudo code i have not tested or ran:
var get_age_gparent = jQuery('.age-check').first();
get_age_gparent.css({'display':'block'});
var get_age_parent = get_age_gparent.find('.ageparent');//add new class on target
var getOptionsDD = get_age_parent.find('.optionsdd');//add new class on target
var getOptionsUL = getOptionsDD.find('.optionsUL');//add new class on target
var getInputNo = getOptionsUL.find('.inputNo');//add new class on target
var getRadioBtnAge = getInputNo.find('input[type=radio].btnage');//add btnage classname to target button
getRadioBtnAge.click(function(){
alert('fffff');
});
In jquery, I have got the html of a particular div on the page and using it as a string. However please can you tell me how I can remove each class in the string called "video-js" and replace it with another div? I am trying to get a few values off each "video-js" div before replacing it with the new div with those values.
This is what I have so far, but it's not writing back to the string.
var getTheCurrentResults = $(".titanLoaderControlList").html();
var obj=$(getTheCurrentResults);
$('.video-js',obj).each(function(){
var theID = $(this).attr("id");
var videoSRC = $(this).find(".vjs-tech").attr("src");
var posterSRC = $(this).find(".vjs-tech").attr("poster");
$(this).text("<div class='playButtonContainer'><div class='playButton'><div class='playButtonSymbol'></div></div></div><div class='videoInfo' data-video-id='"+theID+"' data-source-video='"+videoSRC+"'><img class='posterInfo' src='"+posterSRC+"'></div>");
});
You should be using .html() to replace the HTML content, not .text().
var getTheCurrentResults = $(".titanLoaderControlList").html();
var obj=$(getTheCurrentResults);
$('.video-js',obj).each(function(){
var theID = $(this).attr("id");
var videoSRC = $(this).find(".vjs-tech").attr("src");
var posterSRC = $(this).find(".vjs-tech").attr("poster");
$(this).html("<div class='playButtonContainer'><div class='playButton'><div class='playButtonSymbol'></div></div></div><div class='videoInfo' data-video-id='"+theID+"' data-source-video='"+videoSRC+"'><img class='posterInfo' src='"+posterSRC+"'></div>");
});
I insert a node and when insert another it substitutes the previously inserted one.
I guess I need to put the range after the firstly inserted node, but how?
I define a function:
function EmoticonsMenu(jquery_element){
var e = jquery_element;
var top = e.offset().top;
var left = e.offset().left;
var onIconClick_callback;
this.onIconClick = function(eventObject){
var html = $(eventObject.target).parent().html().replace(/\n\s+|\s+\n/g, '');
onIconClick_callback(html);
};
e.blur(function(){
e.css({visibility:'hidden'});
e.hide();
});
this.attach_to = function(element, callback){
onIconClick_callback = callback;
var newTop = element.offset().top - top - 10 - e.height();
var newLeft = element.offset().left - left + 10;
e.css({top:newTop, left:newLeft});
e.css({visibility:'visible'});
e.focus();
};
};
and there is a place where I bind Emoticon to my nicEditor custom button
nicEditorExampleButton = nicEditorButton.extend({
mouseClick : function(eventObject) {
// get nicEdit selected instance - se
var se = this.ne.selectedInstance;
var paste_icon_html = function(html){
// create a DOM node from the string
//var html = '<img src="/assets/emoticons/ac.gif">admin is here!</img>';
var div = document.createElement('div');
div.innerHTML = html;
var node = div.childNodes[0];
// get selection if any, insert html as a Node
var range = se.getRng();
range.deleteContents();
range.insertNode(node.cloneNode(true));
//range.setStart(node,0);
//range.setEnd(node,0);
};
emoticonsMenu.attach_to($(this.button), paste_icon_html);
}
});
nicEditors.registerPlugin(nicPlugin,nicExampleOptions);
If you don't want to substitute anything, remove the call to deleteContents.
Also you might have the problem that while calling this snippet repeatedly you always refer to the same nodes[0], and it can only exist once - to insert it multiple times, you'd need to clone it:
range.insertNode(nodes[0].cloneNode(true));
Here is code change required. Instead of:
range.insertNode(node.cloneNode(true));
//range.setStart(node,0);
//range.setEnd(node,0);
};
should be
range.insertNode(node);
range.setEndAfter(node); //++
range.setStartAfter(node); //++
};
I have a <ul> "ul-list-one", which contains a number of checkboxes. If I check the checkbox and click the move button it means that it will move to another <ul> "ul-list-two", and the checked checkbox will be removed from the previous, which here would be "ul-list-one".
In "ul-list-two" I can do the same, and it moves to the next, this time "ul-list-three".
Note: "ul-list-two" and "ul-li-three" will be created dynamically.
Here I have done some work, but how can I be able to create multiple <ul>s dynamically?
$('#mer').click( function() {
var txtBox = "";
var txtstatus = false;
$('input[type="checkbox"]').each (function() {
var t = $(this);
var from = 'checklist';
var val=$("#hidden_id").val();
var to = 'ch';
if (!t.is(':checked')){
var swap = to;
to = from;
from = swap;
} else {
txtstatus = true;
}
$(':checkbox:checked').attr('disabled', true);
$('#'+to).append(t.attr('name', to).parent());
$('#ch').addClass('br');
});
if(txtstatus){
txtBox = "<input type='text' value=''>";
$('#ch').after(txtBox);
}
});
//close buttom code
$('#cls').click( function() {
$('input[type="checkbox"]').each (function() {
var t = $(this);
var from = 'checklist';
var to = 'ch';
if (t.is(':checked')){
var swap = to;
to = from;
from = swap;
}
$(':checkbox:checked').attr('disabled', false);
$(':checkbox:checked').attr('checked', false);
$('#'+from).append(t.attr('name', from).parent());
});
});
Not the prettiest thing I have ever written. If you want to leave the empty ul's, just comment out the removeEmpties call. I didn't worry about checkbox order, but it would be easy to implement in a separate function after the checkbox is moved. I also assumed you wouldn't want them to move backward beyond the initial ul. If you want that functionality, you could just add another else if to the move function.
http://jsfiddle.net/pJgyu/13225/