I have a Javascript function in my website. I don't know Javascript very well but, I want to modify it.
This section loads a third drop box, depending on the first two.
I want to modify it to disable the third one if the second drop box locatie's value is util.
jQuery( function () {
jQuery("#util, #loc").change( function() {
var locatie = jQuery("#loc").val();
var utilitate = jQuery("#util").val();
if ( (locatie!= '---') && (utilitate!='---') )
jQuery.getJSON("index.php?option=com_calculator&opt=json_contor&format=raw",{ locatie: locatie, utilitate: utilitate }, function (data) {
var html = "";
html += "<option name=den_contor value ='contor' >Alege Contorul</option>";
if ( data.success == 'ok' )
for (var i in data.val)
html += "<option name=den_contor value ='"+ i+"' >" + data.val[i]+ " </option>";
jQuery("#den_contor").html( html )
})
})
});`
Thanks,
Sebastian
This should work for you:
jQuery( function () {
jQuery("#util, #loc").change( function() {
var locatie = jQuery("#loc").val();
var utilitate = jQuery("#util").val();
if ( (locatie!= '---') && (utilitate!='---') )
jQuery.getJSON("index.php?option=com_calculator&opt=json_contor&format=raw",{ locatie: locatie, utilitate: utilitate }, function (data) {
var html = "";
html += "<option name=den_contor value ='contor' >Alege Contorul</option>";
if ( data.success == 'ok' )
for (var i in data.val) {
if (i != 'locatie' && data.val[i] != 'util') {
html += "<option name=den_contor value ='"+ i+"' >" + data.val[i]+ " </option>";
}
}
jQuery("#den_contor").html( html )
})
})
});
I added the line that starts with if (i != 'locatie' which checks to make sure that you are not looking at the locatie item and that the value is not util. If these are both true (ie. not locatie and not util) then we display the 3rd drop down.
Related
When I dynamically create checkbox and div, I want to have different id for each of them (like id_1, id_2...).
The first value of my array is erased by the next value.
Currently, I create checkbox for each value I have in my array:
var containerCheckbox = $('#listCheckboxCategories');
// var listCheckboxCategories = $('#listCheckboxCategories');
var CheckboxCreate = '<input id="catCheckbox" type="checkbox" name="categoriesCheckbox" required/>';
var categoriesName = '<span id="catName"/>';
if (tileConfig.isThereFilterRadios == "Yes" && res !== undefined) {
$('#ShowCategories').show();
$('#containerCategories').show();
$.each(res.list, function(index, cat) {
//ToDo: inserer cat.name dans le span
// categoriesName.html(cat.name)
containerCheckbox.append(CheckboxCreate, categoriesName);
$("#catName").html(cat.name);
});
}
Can someone help me ?
You could create a function to return the checkbox element, that way you could pass a variable into the function (eg index) to add to the html to make each id unique
for example
createCheckbox = function (index) {
return '<input id="catCheckbox_' + index + '" type="checkbox" name="categoriesCheckbox" required/>';
}
var containerCheckbox = $('#listCheckboxCategories');
var categoriesName = '<span id="catName"/>';
if (tileConfig.isThereFilterRadios == "Yes" && res !== undefined) {
$('#ShowCategories').show();
$('#containerCategories').show();
$.each(res.list, function(index, cat) {
containerCheckbox.append(createCheckbox(index), categoriesName);
$("#catName").html(cat.name);
});
}
I'm working on parsing JSON data and converting it to html form.
I'm using the javascript push function, which I thought would push the data into the array I've designated it to in the order I push it. However, whenever I push a new div element, it is automatically closed after being pushed making the html come out in a different order I want. Is there a way I can prevent this?
JavaScript:
$(function(){
var container = $('.panel-body');
var jsonObj = $.parseJSON('{"fields":[{"label":"Nafn form / Form name","field_type":"sFormName","required":false,"field_options":{"size":"small"},"cid":"c2"},{"label":"Spurning 1 ","field_type":"QuestionText","required":false,"field_options":{"size":"small"},"cid":"c5"},{"label":"Spurning 2","field_type":"QuestionCheckbox","required":false,"field_options":{"options":[{"label":"","checked":false},{"label":"","checked":false}]},"cid":"c9"},{"label":"Spunring 4","field_type":"QuestionRadio","required":false,"field_options":{"options":[{"label":"Val","checked":false},{"label":"VAl ","checked":false},{"label":"Val","checked":false}],"include_other_option":false},"cid":"c13"},{"label":"Spurning með multi","field_type":"QuestionMultiBegin","required":false,"field_options":{"options":[{"label":"","checked":false},{"label":"","checked":false}]},"cid":"c17"},{"label":"Spurning","field_type":"QuestionDropdown","required":false,"field_options":{"options":[{"label":"Val","checked":false},{"label":"Val","checked":false},{"label":"Val","checked":false}],"include_blank_option":false},"cid":"c21"},{"label":"Skráning","field_type":"Registration","required":false,"field_options":{"options":[{"label":"Notendanafn / Username"},{"label":"Lykilorð / Password"}],"include_blank_option":false},"cid":"c25"}]}');
var body = [];
var headerData = jsonObj.fields;
console.log(headerData);
for (var i = 0; i < headerData.length; i++) {
if(jsonObj.fields[i].field_type == "sFormName") {
body.unshift("<div class='panel panel-default panel-element'><div class='panel-heading'>" + jsonObj.fields[i].label)
} else {
body.push("<div class='panel panel-default panel-element'><div class='panel-heading'>" + jsonObj.fields[i].label);
}
if (jsonObj.fields[i].field_type == "QuestionText") {
body.push("<div class='panel-body'><textarea class='large-text form-control'></textarea></div>");
} else if (jsonObj.fields[i].field_type == "QuestionParagraph") {
body.push(jsonObj.fields[i].field_options.description);
} else if (jsonObj.fields[i].field_type == "QuestionDropdown") {
var data = jsonObj.fields[i].field_options.options;
body.push("<div class='panel-body'><div class='dropdown'><button class='btn btn-default dropdown-toggle' type='button' data-toggle='dropdown' id='dropdownMenu1' aria-haspopup='true' aria-expanded='true'>" + jsonObj.fields[i].field_options.options[0].label + "<span class='caret'></span></button>");
body.push("<ul class='dropdown-menu' aria-labelledby=dropdownMenu1'>");
for(var j = 0; j < data.length; j++) {
body.push("<li><a href='#'>" + jsonObj.fields[i].field_options.options[j].label + "</a></li>");
}
body.push("</ul></div></div>");
} else if (jsonObj.fields[i].field_type == "QuestionRadio") {
var data = jsonObj.fields[i].field_options.options;
body.push("<div class='panel-body'>");
for(var j = 0; j < data.length; j++) {
body.push("<div class='radio'><div class='controls'><input type='radio' name='radio'></input>" + jsonObj.fields[i].field_options.options[j].label);
}
body.push("</div></div></div></div>");
} else if (jsonObj.fields[i].field_type == "Registration") {
body.push("<div class='panel-body'>");
body.push("<div class='form-group'><form class='reg-form' role='form'><div class='form-group'><label for='email'>" + jsonObj.fields[i].field_options.options[0].label + "</label>");
body.push("<input type'email' class='form-control' id='email'></div>");
body.push("<div class='form-group'><form class='reg-form' role='form'><div class='form-group'><label for='pwd'>" + jsonObj.fields[i].field_options.options[1].label + "</label>");
body.push("<input type'password' class='form-control' id='pwd'></div>");
body.push("<div class='checkbox'><label><input type='checkbox'> Muna mig / Remember me</label></div></form></div>");
}
$(container).html(body);
}});
As you can see, I wrote the code assuming that I would have to push an ending div to each element that I'd opened, however that seems to be ignored.
The problem here is that you're trying to pass the body array to the html method, however you should instead concatenate all strings inside of it, the pass it.
Like so:
var htmlMarkup = body.reduce(function(){
return prev + current;
}, '');
or use 'join' as suggested by Hacketo, since it's less verbose:
var htmlMarkup = body.join('');
$(container).html(htmlMarkup);
I have created a basket in my PHP form where users can insert their selected movies to it.
Question:
How can I prevent adding duplicate movies to this basket (selected movie list)?
Here is my code: (Sorry, I didn't paste all the code since it was too long)
<div id="basket">
<div id="basket_left">
<h4>Selected Movies</h4>
<img id="basket_img" src="http://brettrutecky.com/wp-content/uploads/2014/08/11.png" />
</div>
<div id="basket_right">
<div id="basket_content">
<span style="font-style:italic">Your list is empty</span>
</div>
</div>
</div>
<script type="text/javascript">
var master_basket = new Array();
$(document).ready(function () {$("input[id='selectType']").change(function(){
// AUTO_COMPLETION PART
$('#btnMove').on('click', function(d) {
console.log(master_basket);
d.preventDefault();
var selected = $("#q").val();
if (selected.length == 0) {
alert("Nothing to move.");
d.preventDefault();
} else {
var obj = {
"movie_name":selected,
"movie_info": ""
};
addToBasket(obj);
}
$("#q").val("");
});
});
function addToBasket(item) {
master_basket.push(item);
showBasketObjects();
}
function showBasketObjects() {
$("#basket_content").empty();
$.each(master_basket, function(k, v) {
$("#basket_content").append("<div class='item_list'>" + v.movie_name + "<a class='remove_link' href='" + k + "'><img width='20' src='http://i61.tinypic.com/4n9tt.png'></a></div>");
});
I personally wouldn't suggest using javascript to prevent this duplication thing since anyone could modify it and manually cause this problem, you should prevent the duplication both in php and javascript.
Anyway to accomplish what you want in the script I think it's enough to modify part of your code to this:
var master_basket = new Array();
selectedMovies = {};
///////
} else {
var obj = {
"movie_name":selected,
"movie_info": ""
};
if(!selectedMovies.hasOwnProperty(selected)){
addToBasket(obj);
selectedMovies[selected] = obj;
}
}
Try modifying your function to
function addToBasket(item) {
var ifExists = false;
for (i = 0; i < master_basket.length; ++i) {
if(master_basket[i] == item)
ifExists = true;
}
if(!ifExists)
master_basket.push(item);
}
}
I'm looking to display a piece of javascript after the 6th paragraph of every post on my wordpress blog. So far, I can only get the function to work when I'm using a fixed variable:
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
$ad_code = 'fixed variable such as <div>box</div>';
if (is_single()) {
return prefix_insert_after_paragraph( $ad_code, 6, $content );
}
return $content;
}
function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
$closing_p = '</p>';
$paragraphs = explode( $closing_p, $content );
foreach ($paragraphs as $index => $paragraph) {
if ( trim( $paragraph ) ) {
$paragraphs[$index] .= $closing_p;
}
if ( $paragraph_id == $index + 1 ) {
$paragraphs[$index] .= $insertion;
}
}
return implode( '', $paragraphs );
}
The javascript I'm trying to add:
function ad_unit() ?>
<script type="text/javascript">
ad = document.getElementById('marker');
if (ad.getBoundingClientRect().width) {
adWidth = ad.getBoundingClientRect().width;
} else {
adWidth = ad.offsetWidth; // for old IE
}
/* Choose the right ID */
if ( adWidth >= 600 )
aId = ["test1"];
else if ( adWidth >= 468 )
aId = ["test2"];
else
aId = ["test3"];
document.write (
'<div id="' + akId[0] + '"></div>'
);
</script>
<?php
I've tried to declare $placeholder = ad_unit(); but it keep displaying the unit at the top of the content instead of after the 6th paragraph. Somehow the prefix_insert_after paragraph function doesn't work after I add the javascript function. Any ideas?
Try it with ob_start() and ob_get_clean()
function ad_unit()
{
ob_start();
?>
<script type="text/javascript">
ad = document.getElementById('marker');
if (ad.getBoundingClientRect().width) {
adWidth = ad.getBoundingClientRect().width;
} else {
adWidth = ad.offsetWidth; // for old IE
}
/* Choose the right ID */
if ( adWidth >= 600 )
aId = ["test1"];
else if ( adWidth >= 468 )
aId = ["test2"];
else
aId = ["test3"];
document.write ('<div id="' + akId[0] + '"></div>');
</script>
<?php
return ob_get_clean();
}
So what happens is that with ob_start() you enable output buffering. You output the HTML but buffer it, then with ob_get_clean() you get the buffered output from the output buffer.
This will be cleaner without a function (and definitely work, I don't remember what plain HTML does when put in a PHP function):
// Somewhere above the rest of your application
ob_start(); ?>
/// YOUR HTML/javascript
<?php
$advertisement = ob_get_clean();
You need opening and closing brackets for the php function
<?php
function ad_unit() { ?>
<script type="text/javascript">
ad = document.getElementById('marker');
if (ad.getBoundingClientRect().width) {
adWidth = ad.getBoundingClientRect().width;
} else {
adWidth = ad.offsetWidth; // for old IE
}
/* Choose the right ID */
if ( adWidth >= 600 )
aId = ["test1"];
else if ( adWidth >= 468 )
aId = ["test2"];
else
aId = ["test3"];
document.write (
'<div id="' + akId[0] + '"></div>'
);
</script>
<?php }
This function replicates the user experience of a Select/MultiSelect dropdown element - displaying the values of checkboxes checked in a container (adds/removes them when they're checked/unchecked), and if more than 3 items have been checked it displays the # selected instead of the values selected.
It's a combination of 2 functions and they're not playing well together when items are unchecked (i.e. it's removing the values but not the commas, doesn't work correctly when more than 3 items have been selected, etc.)
I think it would be much better if I used an array to store the values, adding/removing values from the array when items are checked/unchecked, and I know how do to in PHP but not in Javascript. This code should create the array, but I can't figure out how to integrate it into my code.
$('input:checkbox[name="color[]"]:checked').each(function () {
selectedColors.push($(this).val());
});
Existing Code:
JS
$(".dropdown_container ul li").click(function () {
var text = $(this.children[0]).find("input").val();
var text_edited = text.replace(/_/g, " ");
var currentHtml = $(".dropdown_box span").html();
var positionLocation = currentHtml.indexOf(text_edited);
var numberChecked = $('input[name="color[]"]:checked').length;
if (positionLocation < 1) {
if (numberChecked <= 3) {
$(".dropdown_box span").html(currentHtml.replace('Colors', ''));
$(".dropdown_box span").append(', ' + text_edited);
} else {
$(".dropdown_box span").html(currentHtml.replace(currentHtml, numberChecked + " Selected"));
}
} else {
(currentHtmlRevised = currentHtml.replace(text_edited, ""));
$(".dropdown_box span").html(currentHtmlRevised.replace(currentHtml));
}
});
HTML
<div class="dropdown_box"><span>Colors</span></div>
<div class="dropdown_container">
<ul id="select_colors">
<li>
<label><a href="#"><div style="background-color: #ff8c00" class="color" onclick="toggle_colorbox_alt(this);"><div class=CheckMark>✓</div>
<input type="checkbox" name="color[]" value="Black" class="cbx"/>
</div>Black</a></label>
</li>
<!-- More List Items --!>
</ul>
</div>
Easiest to just replace the entire content each time. Also use the change event instead of the click event.
$(".dropdown_container input").change(function () {
var checked = $(".dropdown_container input:checked");
var span = $(".dropdown_box span");
if (checked.length > 3) {
span.html("" + checked.length + " selected");
}
else {
span.html(checked.map(function () { return $(this).val().replace("_"," "); }).get().join(", "));
}
});
Example: http://jsfiddle.net/bman654/FCVjj/
try this:
$('.cbx').change(function(){
var cbx = $('.cbx:checked');
var str = '';
if (cbx.length<=3 && cbx.length!=0){
for (var i=0;i<cbx.length;i++){
if (i>0) str += ', ';
str += cbx[i].value;
}
} else if (cbx.length==0){
str = 'Colors';
} else {
str = cbx.length;
}
$('.dropdown_box span').html(str);
});