i'm trying to display certain sentences and images according to the value of a select menu.
If an user selects that his platform is "Android", then he'll see an specifc message. If he selects that his platform is "iOS", then he will see another.
I want to achieve this using a variable "isAndroid", if it is true it will display the Android message plus the android icon and if it is false it will display the iOS message and the iOS icon.
Then i implemented the jquery method "change()" to being able to swtich and change the content whenever the selector value is changed between "Android" and "iOS". I've managed to achieve my objective in a different and more complicated way, but i want to do it with this boolean to use it on more stuff later, if "isAndroid" is true it will do many other things, but i'm showing the basic here to keep it simple.
This is my actual HTML and Javascript code:
function platformAndroid() { //function with the content of Android. it should run if "esAndroid" is true
$("#iconoDispositivo").attr("src","http://i.imgur.com/ksYWdrF.png");
$("#chosenPlatform").html("Your chosen platform was android");
}
function platformIos(){ //function with the content of iOS. it should run if "esAndroid" is false
$("#iconoDispositivo").attr("src","http://i.imgur.com/YPqQsib.png");
$("#chosenPlatform").html("Your chosen platform was iOS")
}
var isAndroid = true;
function dispositivoStart(){ // this functions displays the correct stuff when user refresh the page
if($('#dispositivo').val() === "Android"){ //if my select input value is android, then "esAndroid" is true
isAndroid;
} else {
isAndroid = false; // otherwise it is false
}
$('#dispositivo')on.("change",function(){ //here i wrote this piece of code to switch "esAndroid" to true or false when they select different values on the selector input
if($(this).val() === "Android"){
isAndroid;
} else {
isAndroid = false;
}
})
if(isAndroid){ // here is the piece of code that displays the content. if esAndroid is true, then the function that displays "Android" content runs.
platformAndroid()
} else {
platformIos() //if "esAndroid" is false, then the function that displays "iOS" content runs
}
}
dispositivoStart();
#chosenPlatform {
font-size: 20px;
color: green;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>
Platform choose
</title>
</head>
<body>
<h2>Platform</h2>
<div class="field">
<label for="dispositivo">Choose your platform</label><br>
<select id="dispositivo">
<option>Android</option>
<option>iOS</option>
</select>
</div>
<div class="field">
<p id="chosenPlatform">Your chosen platform was Android</p> <img src="http://i.imgur.com/ksYWdrF.png" width="32" alt="androidIcon" id="iconoDispositivo">
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/core.js"></script>
</body>
</html>
I can't understand why in the snippet i can't call jquery correctly, in my own files i use cdns, but that's the code that i'm trying to run.
With the current code, the boolean from "isAndroid" changes to false, but doesn't display the content that it should display when "isAndroid" is false (the iOS content). It also doensn't switch back to true when the select input value switchs to "Android" again.
As i said at the beggining, i could achieve my objetive if i use
#dispositivo.val() === "Android"
but i think that doing "isAndroid" = true/false is simpler, becouse later on i have to keep using that boolean to display certain content depending on that selector value.
I hope i was clear enough, this is my second question written on Stackoverflow, thanks in advance.
Before we address your primary issue, we should address your HTML. Run the HTML through a validator (not W3C, it's outdated). The demo features a working example of HTML content being inserted into a <section> and values being set in an <output> form control, which is determined by a user's selection of a <select>.
Methods, Properties & Processes
jQuery
.on() Event Delegation
.html(), .text(), & .val()
JavaScript
ES6 Template Literals
switch()
Details are commented in demo
Demo
/* NOTE: ES6 Template Literals are being used instead of
|| String Literals:
[Example: String Literal >>>
var SL = "This is a String, this is a " + variable\
+ " concatenated";
[Example: Template Literal >>>
var TL = `This is a String, this is a ${variable}
interpolated`;
*/
/* Register change event on the select#mobile
|| .on() method delegates events. Main advantage
|| of delegating events is that the event will
|| be registered not only for elements currently
|| in DOM, but elements that will be there in the
|| future.
*/
/* Callback function is getContent which is invoked
|| upon a change event occurring on #mobile
*/
$('#mobile').on('change', getContent);
function getContent(e) {
// Store the value of a form control (i.e. #mobile)
var opt = this.value;
/* Pass value to a switch(). A switch() method is
|| a if/if else condition that's easier to read.
*/
switch (opt) {
// if (opt === 'android') {...
case 'android':
/* If getting/setting data of a form control
|| use .val() method.
|| ex. input, output, select, etc..
*/
// Change the value of output#out
$('#out').val(`Selected OS is Android`);
/* If getting/setting content between an element's
|| tags use .html() or .text() methods
|| ex. <div>CONTENT</div>
*/
// Change the HTML of section.dock
$('.dock').html(
`<h1>Samsung Galaxy</h1>
<label>Model: <input></label>
<button>DONE</button>`);
break;
case 'iOS':
$('#out').val(`Selected OS is iOS`);
$('.dock').html(
`<h1>iPhone</h1>
<label>Model: <input></label>
<button>DONE</button>`);
break;
/* If its neither 'android' nor 'iOS', then it
|| refers to default case. In this particular case
|| output#out and section.dock will be erased.
*/
default:
$('#out').val('');
$('.dock').html('');
break;
}
}
select,
input,
button,
label {
font: inherit
}
<form id='interface'>
<select id='mobile'>
<option value='-'>-------------</option>
<option value='android'>Android</option>
<option value='iOS'>iOS</option>
</select>
<output id='out'></output>
</form>
<section class='dock'></section>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Related
Have a page containing links.
When a link is clicked I want Javascript (or other) to check if the link contains (e.g. cheese)
If if does, then a modal should launch displaying the link.
example:
http://mylink/just-normal/ -- when this clicked, should proceed as normal
http://mylink/with-cheese/ -- when this clicked, should launch modal
http://mylink/another-link/ -- when this clicked, should proceed as normal
http://mylink/other-link/ -- when this clicked, should proceed as normal
Modal should display the full link.
Any assistance is appreciated.
Below is what I've got so far.
My specific question is:
Question: When I click any link on the site, a modal opens. It seems to be targeting all links and not just the links containing the specific word(s).
jQuery(function () {
jQuery(document).on('click', jQuery('a') , function(event){
var e = event;
event.preventDefault;
var that = event.target;
if(jQuery(that).is("span")){
that = jQuery(event.target).parent();
}
if(jQuery(that).attr('href')){
var url = jQuery(that).attr('href').toLowerCase();
if(jQuery.browser.webkit || jQuery.browser.mozilla && (url.indexOf('.my.test.here/') >=0)) {
ie_pointer(e, that);
}
else if (jQuery.browser.webkit && || jQuery.browser.mozilla (url.indexOf('something.else/') >=0)){
var overall = jQuery('.overall');
ie_pointer(e, overall, that);
}
}
});
});
function ie_pointer(event, obj, that){
event.preventDefault();
if(that){
var url = jQuery(that).attr('href');
}
else{
var url = jQuery(obj).attr('href');
}
jQuery('<div class="modal-backdrop"></div>').hide().appendTo(document.body).fadeIn();
jQuery(obj).after('<div class="modal-content" style="padding:10px"><h3 style="color:#333">Please copy the blue link below into Internet Explorer</h3><p style="font-size: 1.2rem; color:#333">This form is currently unavailable in Firefox & Chrome.</p><h4 style="color: #0099cc; max-width: 400px; word-wrap:break-word;">'+url+'</h4><i onclick="close_modal()" class="icon-remove"></i></button></div>');
}
function close_modal(){
jQuery(".modal-backdrop").fadeOut(function(){jQuery(this).remove()});
jQuery('.modal-content').fadeOut(function(){jQuery(this).remove()});
}
Your click event handler is set up for event delegation so that it only responds when event.target is an <a>:
jQuery(document).on('click', jQuery('a') , function(event){
Yet, inside of the handler, you have this:
if(jQuery(that).is("span")){
that = jQuery(event.target).parent();
}
Since you have that set to event.target, this if condition will never be true, so I'm not sure what you are trying to accomplish with it.
The remainder of the function runs when the <a> element has an href, but there too, you have if conditions that don't quite make sense:
if(jQuery.browser.webkit ||
jQuery.browser.mozilla && (url.indexOf('.my.test.here/') >=0)) {
ie_pointer(e, that);
} else if (jQuery.browser.webkit && ||
jQuery.browser.mozilla (url.indexOf('something.else/') >=0)){
var overall = jQuery('.overall');
ie_pointer(e, overall, that);
}
Your first condition will be true if the browser is webkit or if it is mozilla and the attribute contains your test string. Why don't you want to test for the string when the browser is webkit?
Your else if condition does the same thing, but you have a syntax error in it because you forget && here:
jQuery.browser.mozilla (url.indexOf('something.else/') >=0))
And, perhaps more importantly, why do you care what browser it is? JQuery deprecated the browser flags in version 1.9 because they are based on the navigator.userAgent, which has always been an unreliable way of browser sniffing.
Here's a slimmed down example of getting links that contain a certain string in their href to do one thing and all others to do something else using the standard CSS attribute selector:
var url = "console";
// Simply use the attribute wildcard selector to make sure
// you are only selecting links you care about in the first place
$("a[href*='" + url + "']").on("click", function(evt){
evt.preventDefault();
alert("You clicked a link that I care about!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I should cause an alert().<br>
I should cause an alert().<br>
I should NOT cause an alert().<br>
I should NOT cause an alert().
I'm trying to build an Angular Tag Directive that functions not too dissimilarity from Stack Overflow's Tag input form. It uses a div with a border to create the illusion of a form, and then a div containing a list of tags to the left of an input field where you can type:
<div class="wrapper">
<div class="tag-wrapper">
<div class="tags" ng-repeat="tag in selectedTags">
<div>
[[ tag.name ]]
<span class="remove" ng-click="removeTag(tag)"></span>
</div>
</div>
</div>
<input type="text" class="tag-input"
ng-model="tagInput"
ng-style="{ width: inputLength + 'px'}"
ng-keypress="tagInputKeyPress($event)"
ng-keyup="updateSuggestionList()"
ng-focus="toggleSuggestionVisibility()"
ng-blur="toggleSuggestionVisibility()" />
</div>
Please note I'm using [[]] as my interpolation provider for Angular because I have another templating engine already using {{}}.
When a key is pressed in the input, it runs a function to check if the key is a backspace or enter or a space to create/remove a tag:
$scope.tagInputKeyPress = function(event) {
// Currently using jQuery.event.which to detect keypresses, keyCode is deprecated, use KeyboardEvent.key eventually:
// https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key
// event.key == ' ' || event.key == 'Enter'
if (event.which == 32 || event.which == 13) {
event.preventDefault();
// Remove any rulebreaking chars
var tag = $scope.tagInput;
tag = tag.replace(/["']/g, "");
// Remove whitespace if present
tag = tag.trim();
$scope.createTag(tag);
// event.key == 'Backspace'
} else if (event.which == 8 && $scope.tagInput == "") {
event.preventDefault();
// grab the last tag to be inserted (if any) and put it back in the input
if ($scope.selectedTags.length > 0) {
$scope.tagInput = $scope.selectedTags.pop().name;
}
}
$scope.inputLength = $(element).find('input.tag-input').parent().innerWidth() - $(element).find('.tag-wrapper').outerWidth() - 1;
return true;
};
The bit I'm having problems with is the last line before the return statement. What it is meant to do is recompute the width of the .tag-wrapper element and adjust the width of the input element to suit via this ng-style property:
ng-style="{ width: inputLength + 'px'}"
However, as it currently stands, the input length is always one step behind the UI, causing the input to overflow. This is because:
It firstly adds a new tag onto the selectedTags list.
It computes the width of .tag-wrapper.
It returns true letting the original key event pass through
Angular's digest cycle runs and appends a new tag into the DOM. The width of .tag-wrapper is now bigger, and the input overflows.
Here is an example of this:
Right now, step 4 is happening after step 2. I need step 2 to happen after step 4.
How can I achieve this?
You modify your createTag method to have a callback, and set the inputLength within the callback.
Alternative hack: wrap the setting of inputLength within a $timeout, to force the the line to be executed in the following digest call.
I need to put span tags around first word in a line. I used the below Jquery which is working fine in sitecore standard mode.
$("body").has(".widget h2").addClass("standard-mode");
$("body").has(".scLoadingIndicatorInner").removeClass("standard-mode").addClass("page-edit");
$('.standard-mode .widget h2').html(function(i, html){
return html.replace(/(\w+\s)/, '<span>$1</span>')
})
When i first load the page editor this works fine as well(by not inserting the span tags), but when i created a multivariate test switching between the A/B by using arrow marks shows like inserting the span tags which it should not suppose to do as it is in page-edit mode but it does and breaking the html as below.
<h2>
<<span>input </span>id="fld_D26C954B73BE4C62B6F25BE191A86F18_7B55B5E5EDD84D4E88B16C6E073495A5_en_1_0e80a9c63ab6419f8135b70511e892f1_16487" class="scFieldValue" name="fld_D26C954B73BE4C62B6F25BE191A86F18_7B55B5E5EDD84D4E88B16C6E073495A5_en_1_0e80a9c63ab6419f8135b70511e892f1_16487" type="hidden" value="Badger Cull"><span class="scChromeData">{"commands":[{"click":"chrome:common:edititem({command:\"webedit:open\"})","header":"Edit the related item","icon":"/temp/IconCache/SoftwareV2/16x16/cubes_blue.png","disabledIcon":"/temp/cubes_blue_disabled16x16.png","isDivider":false,"tooltip":"Edit this item in the Content Editor.","type":"common"},{"click":"chrome:rendering:personalize({command:\"webedit:personalize\"})","header":"Personalize","icon":"/temp/IconCache/PeopleV2/16x16/users3_edit.png","disabledIcon":"/temp/users3_edit_disabled16x16.png","isDivider":false,"tooltip":"Personalize component.","type":"sticky"},{"click":"javascript:Sitecore.PageModes.PageEditor.postRequest('ActiveISPageEditor:publish(id={D26C954B-73BE-4C62-B6F2-5BE191A86F18})',null,false)","header":"Publish the related item","icon":"/temp/IconCache/Network/16x16/download.png","disabledIcon":"/temp/download_disabled16x16.png","isDivider":false,"tooltip":"Publish this item.","type":"common"},{"click":"chrome:rendering:editvariations({command:\"webedit:editvariations\"})","header":"Edit variations","icon":"/temp/IconCache/SoftwareV2/16x16/breakpoints.png","disabledIcon":"/temp/breakpoints_disabled16x16.png","isDivider":false,"tooltip":"Edit the variations.","type":"sticky"}],"contextItemUri":"sitecore://master/{D26C954B-73BE-4C62-B6F2-5BE191A86F18}?lang=en&ver=1","custom":{},"displayName":"Header Text","expandedDisplayName":null}</span><span scfieldtype="single-line text" sc_parameters="prevent-line-break=true" contenteditable="false" class="scWebEditInput scEnabledChrome" id="fld_D26C954B73BE4C62B6F25BE191A86F18_7B55B5E5EDD84D4E88B16C6E073495A5_en_1_0e80a9c63ab6419f8135b70511e892f1_16487_edit" sc-part-of="field">Badger Cull</span>
</h2>
Any suggestions will be helpful.
You can check the JavaScript property Sitecore.PageModes.PageEditor to see if you are in page editor mode and can disable your javascript accordingly.
function isPageEditor() {
if (typeof Sitecore == "undefined") {
return false;
}
if (typeof Sitecore.PageModes == "undefined" || Sitecore.PageModes == null) {
return false;
}
return Sitecore.PageModes.PageEditor != null;
}
if (isPageEditor() == false) {
//do your stuff here
}
I wring a code to show hint to user in textarea in grey color;
Idea is next:
1) Initially in area is "Please, type your enquiry there" in grey color;
2) if user click on it, color change to black and text to ''. This part works fine
3) if user type, but than delete (i.e. left field blank) than we need to put "Please, type your enquiry there" in grey color; And this do not work non in Chrome, non in Firefox.It display nothing. When I use chrome inspector, it shows
element.style { color: rgb(141, 141, 141); }
what is right and "Please, type your enquiry there" in HTML what is also right, but field is empty. What might be the problem???
I specially put console.log and they also display output that should be...
This is HTML:
<textarea name='contact_text' id='contact_text'
onclick='text_area_text_cl();' onBlur='text_area_text_fill();'>
</textarea>
<script>
var contact_text_changed = false;
var contact_contacts_changed = false;
function text_area_text()
{
if (contact_text_changed == false)
{
$("#contact_text").css("color","#8d8d8d");
$("#contact_text").html('Please, type your enquiry there');
}
else
{
$("#contact_text").css("color","#000000");
}
// Write your code here
};
function text_area_text_cl()
{
if (contact_text_changed == false)
{
$("#contact_text").text('');
$("#contact_text").css("color","#000000");
console.log('sdfdfs111');
contact_text_changed = true;
}
};
function text_area_text_fill()
{
if ($("#contact_text").val() == '')
{
contact_text_changed = false;
$("#contact_text").css("color","#8d8d8d");
$("#contact_text").html('Please, type your enquiry there');
//document.getElementById('contact_text').innerHTML = 'Please, type your enquiry there'
console.log('sdfdfs');
}
else
{
console.log('__');
}
};
// call funcitons to fill
text_area_text();
</script>
To set the value of a <textarea> you need to use .val():
$("#contact_text").val('');
or
$("#contact_text").val('Please, type your enquiry there');
etc. It's tricky to make "placeholder" code work properly. Newer browsers allow:
<textarea placeholder='Please, type your enquiry there' id='whatever'></textarea>
and they manage it all for you.
edit — from the comments, here's an explanation as to why it appears that .html() works (well, it does work, but read on) initially. The markup contents of a <textarea> element — that is, the DOM structure contained within the element — represents the initial value of the <textarea>. Before any user interaction (and/or before the "value" property of the DOM has been touched by JavaScript), that's what's shown as the value of the field. Changing that part of the DOM, then, changes that initial value. Once there's been some user interaction, however, the initial value is no longer relevant to the page view, so it's not shown. Only the updated value is shown.
Want to have a notification box displayed if amount in fieldA is higher than amount in fieldB.
Currently have some code working but the notification box toggles on and off not depending on the actual amount.
What am I missing?
jquery:
$(document).ready(function() {
$('#fieldA').change(function(){
if($(this).val()>$('#fieldb').val()){
//display it on the form
$('.labelNotification').toggle();
$('.labelNotification').append('Not recommended to have FieldA figure higher than FieldB.');
}
})
});
HTML:
< p style="display: none;" class="error labelNotification">
This is tailor-made for the toggle(boolean) method. Also, you have to be careful about appending to the notification label ... what if the user changes his answer twice? It's better to have multiple notification objects, each of which can contain stuff for a single type of notification.
$(function() {
$('#fieldA').change(function() {
var isLarger = +$(this).val() > +$('#fieldB').val(); // Note: convert to number with '+'
var $labelNotification = $('.labelNotification');
$labelNotification.toggle(isLarger);
if (isLarger) {
//display it on the form
$labelNotification.html('Not recommended to have FieldA figure higher than FieldB.');
}
})
});
If you're comparing numerical values (which it seems like you are), you should use parseInt or parseFloat to convert the (string) value returned by val() to an integer. According to the documentation for val, the function always returns a string value.
I found the problem ,
First thing is you need to have semicolon properly as below
$('#fieldA').change(function () {
if ($(this).val() > $('#fieldB').val()) {
alert("its greater");
//display it on the form
$('.labelNotification').append('Not recommended to have FieldA figure higher than FieldB.');
$('.labelNotification').show();
}
else {$('.labelNotification').hide();
$('.labelNotification').html('');}
});
Second thing , when you toggle it it won't show for the second time
if 40 > 30
and again if you entery 50 and 50 > 30 it won't show
this is second problem
final problem is empty the label all the time
$('.labelNotification').html('')'
Toggle is not the best approach for your situation.
You want to compare and then decide.
Since you are looking at numbers I would strongly suggest using a number type to do the comparison, either using parseInt() or parseFloat().
The text in the notification label only needs to be set once, since you don't have any comment for it showing something when B > A. I would suggest setting this in your HTML.
<span class="labelNotification" style="display:none">Your Warning Text</span>
<!-- if your CSS class has `display:none` remove the style attribute -->
as for the jQuery.
$(function() {
$("#fieldA").change(function() {
var a = parseInt($(this).val());
var b = parseInt($("#fieldb").val());
// handle if a or b is not a number --> isNaN(a) || isNaN(b)
if( a > b ) {
$('.labelNotification').show()
} else {
$('.labelNotification').hide()
}
});
});