How to display javascript variables in html - javascript

I have the the following javascript variables.
goalDiv ="<div class=goal-parent id=goal-parent"+Id+">"+
"<div class=goal>"+
"<div class=top-layer>"+
"<div class=component>"+
"<select class=component-select>"+
"<option id=one><span id='source_name'></span></option>"+
"</select>"+
"</div>"+
"</div>"+
"</div>"+
"</div>";
Id = "some div value";
I am trying to show values inside these divs. I first show this goalDiv into a div and then try to update the values inside it, like following.
document.getElementById(Id).innerHTML = goalDiv;
document.getElementById('source_name').innerHTML = "some value";
The first innerHTML works but the second doesn't. What am i doing wrong?

You can't have span inside option.
If you want to change the dropdown options simply use:
document.getElementById('one').innerHTML = "some value";

Related

Dynamically Added ng-model in custom directive does not work

I have searched for this question on Stackoverflow, but all are different from this one. Although the question might be the same the implementation is different.
This directive accepts an array of JSON called config. Which contains properties of an input or a dropdown. I also receive the variable that has to be binded within ngModel. Everything works fine like ng-maxlength ng-minlength but ng-model does not. I cannot fetch the values or in simple words there is no two way binding. Also to get all the values within a single object I append a string called pgCard within the name attribute in the custom directive. To make it look like pgCard.* to use it directly as a json object. But all in vain. I even tried removing the pgCard but of no use.
Below is my custom directive Element markup
<program-gateway config="configArrayCard" name="pgCard"></program-gateway>
This is my custom directive.
app.directive('programGateway',['$compile',
function($compile){
return {
restrict : 'E',
replace :true,
template:"<div class='row'></div>",
scope:{
config:"=",
name:"#"
},
link: function(scope,e,attr){
var modelPrefix=scope.name+"." || "";
var field="",model="";
var max="",min="",maxlen="",req="",options="";
var leftHTML="",rightHTML="",innerHTML="";
scope.config=sortByKey(scope.config,"propertyKey");
angular.forEach(scope.config,function(value,key){
model=modelPrefix+value.propertyKey;
var midLen=(Math.floor(scope.config.length/2))+(Math.floor(scope.config.length%2));
if(!value.propertyInfo.selection){
if(value.propertyInfo.hasOwnProperty("max")){
max="data-ng-maxlength='"+value.propertyInfo.max+"'";
maxlen="maxlength='"+value.propertyInfo.max+"'"
} if(value.propertyInfo.hasOwnProperty("min")){
min="data-ng-minlength='"+value.propertyInfo.min+"'";
}
req=(value.propertyInfo.optional)?"":"required";
field="<input "+req+" class='form-control' type='text' id='"+model+"' data-ng-model='"+model+"' "+max+" "+min+" "+maxlen+">";
}else{
var optArr="[\""+(value.propertyInfo.selectionOptions).replace(/,/g, '","')+"\"]";
field="<select data-ng-options='opt for opt in "+optArr+"' "+req+" data-ng-model='"+model+"' class='form-control' id='"+model+"'>"+
"<option value=''>Select </option>"+
"</select>";
}
if(key<midLen){
leftHTML+="<div class='form-group'>"+
"<label for='"+value.propertyInfo.propertyLabel+"' class='col-sm-5 control-label'><span data-ng-hide='"+value.propertyInfo.optional+"' class='red'>*</span>"+value.propertyInfo.propertyLabel+":</label>"+
"<div class='col-sm-7'>"
+field+
"</div>"+
"</div>";
}else{
rightHTML+="<div class='form-group'>"+
"<label for='"+value.propertyInfo.propertyLabel+"' class='col-sm-5 control-label'><span data-ng-hide='"+value.propertyInfo.optional+"' class='red'>*</span>"+value.propertyInfo.propertyLabel+":</label>"+
"<div class='col-sm-7'>"
+field+
"</div>"+
"</div>";
}//if closed
});// for closed
innerHTML="<div class='col-sm-6'>"+leftHTML+"</div>"+
"<div class='col-sm-6'>"+rightHTML+"</div>";
e.html(innerHTML);
scope.$watch(function() {
return scope.pgCard = scope.pgCard;
});
$compile(e.contents())(scope);
}
}
}]);
This is the snap of the json that I receive
"config":[{"propertyKey":"reportGroup","editable":true,"propertyInfo"
:{"max":3,"optional":true,"propertyLabel":"Report Group","selection":false}},{"propertyKey":"sendStatementToCompany"
,"propertyValue":"Yes","editable":true,"propertyInfo":{"optional":false,"propertyLabel":"Send Statement
to Company","selection":true,"selectionOptions":"Yes,No","defaultValue":"Yes"}}]
Please help am I doing something wrong.

Selected option disappears when button is pressed

I have a file, template.php, which contains a JS function to add some dropdown box options to the page, so the user can add as many more options as they wish.
My issue is, if the user has selected some options within those select boxes, and then presses the "addsunday" button to add more boxes, the previously chosen options are cleared (so every dropdown on the page resets to 00:00).
I'd like to know what is causing the selections to reset and how I can get around this problem.
$("#addsunday").click(function() {
var htmlstring = "<div class='shiftwrapper'>";
htmlstring += "<select data-col-id='start' form='newtemplateform'>";
htmlstring += "<?php
for($hours=0; $hours<24; $hours++) // the interval for hours is '1'
for($mins=0; $mins<60; $mins+=30) // the interval for mins is '30'
echo '<option>'.str_pad($hours,2,'0',STR_PAD_LEFT).':'
.str_pad($mins,2,'0',STR_PAD_LEFT).'</option>';?>";
htmlstring += "</select>";
htmlstring += "<select data-col-id='finish' form='newtemplateform'>";
htmlstring += "<?php
for($hours=0; $hours<24; $hours++) // the interval for hours is '1'
for($mins=0; $mins<60; $mins+=30) // the interval for mins is '30'
echo '<option>'.str_pad($hours,2,'0',STR_PAD_LEFT).':'
.str_pad($mins,2,'0',STR_PAD_LEFT).'</option>';?>";
htmlstring += "</select>";
htmlstring += "<select data-col-id='loc' form='newtemplateform'>";
htmlstring += "<?php foreach($locations as $location){ print '<option value=\"$location\">' . $location . '</option>\n'; }?>";
htmlstring += "</select>";
htmlstring += "<button class='removeshift'>Remove Shift</button><br/>";
htmlstring += "</div>";
document.getElementById('sundaywrap').innerHTML += htmlstring;
console.log("Sunday clicked");
});
I apologise if this is a really inefficient way to repeat code, I'm still learning.
Here's a really bad fiddle: https://jsfiddle.net/L7npxvzp/
It doesn't work however you can see the structure of how the dropdowns work. There's a button to add more dropdowns, it is when this button is pressed that the previously changed selections reset back to their defaults.
The problem is this line:
document.getElementById('sundaywrap').innerHTML += htmlstring;
This replaces the DOM elements in #sundaywrap with new DOM elements that come from parsing the HTML after you've concatenated htmlstring. Any dynamic state in the old DOM elements, such as selected items from a menu, is lost.
Instead of concatenating to the HTML, you should append to the DOM:
$("#sundaywrap").append(htmlstring);

Parsley doesn't work after appending html

I tried following code, but it doesn't notify when there's no data in the input box. When I directly add this content (without) appending it works. What am I doing wrong here
var output = "<form class=\"registration__form\">\n"+
"<ul class=\"form-fields\">\n"+
"<li>\n"+
"<input type=\"text\" name=\"msisdn\" id=\"field-msisdn\" placeholder=\"Enter your MSISDN\" autofocus required data-parsley-required-message=\"Please insert your MSISDN\">\n"+
"</li>\n"+
"<li>\n"+
"<input type=\"button\" class=\"btn btn--large btn--fill btn--full\" value=\"Reset PIN\" onclick=\"submitMSISDN($('#field-msisdn').val());\"/>\n"+
"</li>\n"+
"</ul>\n"+
"</form>";
$("#gadgetBody").empty();
$("#gadgetBody").append(output);
$("#gadgetBody").parsley();
You have to call parsley() on the form, not on whatever contains the form.
In your case: $("#gadgetBody form").parsley() should work.

Value not passing properly in javascript function while iterator using $.each() function

I am returning array of object called "categories" from the Ajax call and then i am replacing its object(category) value in the string(categoriesList). Then i am replacing this string in the html div Area as $("#divAreaName").html("StringName");
For proper understanding the code is shown below:
$.each(categories,function(index,category){
categoriesList = categoriesList +
"<div class='media'>"+
"<img onclick=dispProductCategoryWise('"+category.name+"','"+category.id+"','"+id+"','"+retailerId+"'); src='${pageContext.request.contextPath}"+category.image+"'>"+
"</div>"+
"<div class='item-info'>"+
"<div class='item-name item-row'>"+
"<span class='full-item-name'>"+category.name+"</span>"+
"</div>"+
"</div>";
});
Then i am replacing the string in the div area using the following line of code
$("#divName").html(categoriesList);
However the problem is when category.name is "Fruits and Vegetable". The HTML is formed as shown below:
<img onclick="dispProductCategoryWise('Fruits" &="" Vegetable','60','1','2');="" src="/closerby/images/customer/category/FandV.jpeg">
Can someone let me know why the values are not getting passed properly and the possible solution?
Interesting problem, it seems the spaces are strangely converted when using .html(). As if the '/" itself are rendered. console.log gives correct string as well.
As an alternative, create an event on that specific image using a dynamically generated id.
Like so:
categories = {
"category":{
"name": "Fruits and Vegetables",
"id": 1,
}
}
$.each(categories,function(index,category){
categoriesList =
"<div class='media'>"+
"<img id='specific_"+index+"' src='{somethingwashere}'>"+
"</div>"+
"<div class='item-info'>"+
"<div class='item-name item-row'>"+
"<span class='full-item-name'>"+category.name+"</span>"+
"</div>"+
"</div>";
$("#myDiv").html(categoriesList);
//Added event.
$('#specific_'+index).click(function() {
return displayProductCategoryWise(category.name, category.id);
});
});
function displayProductCategoryWise(name, id) {
alert(name);
alert(id);
}
Ive only used $('selector').each(fn) to do something for each matched jquery element
Perhaps try using categories.forEach(function(category, index){ ...
Are you turning the quote makes into special characters..... add a blackslash ()
Something like :
<img onclick=dispProductCategoryWise('\"+category.name+\"','\"+category.id+\"','\"+id+\"','\"+retailerId+\"'); src='${pageContext.request.contextPath}\"+category.image+\"'>\"

show div based on textbox value

I have a input field that gets it value from a db lets say the value is M,K,H,J,V or G depending on the value it needs to open the div with aaa,bbb,ccc,ddd,eee or fff as text.
The code that is displayed on the page is as followed i left out the retrieval part from the db that part is working (the input box shows M,K,H,J,V or G depending on the id.)
echo "<input type='text' name='periode' id='periode' data-related-item='" .$row['periode']. "' value='" .$row['periode']. "'>";
echo "<div class='hidden'><div id='M'>aaa</div></div>";
echo "<div class='hidden'><div id='K'>bbb</div></div>";
echo "<div class='hidden'><div id='H'>ccc</div></div>";
echo "<div class='hidden'><div id='J'>ddd</div></div>";
echo "<div class='hidden'><div id='V'>eee</div></div>";
echo "<div class='hidden'><div id='G'>fff</div></div>";
When i check the source code in developer mode it shows that the data-related-item part is correctly retrieved from the db:
<input type="text" name="periode" id="periode" data-related-item="M" value="M">
I want to use the following JS but i need to change it to work with textboxes.
<script type="text/javascript">
function evaluate1(){
var item = $(this);
var relatedItem = $("#" + item.attr("data-related-item")).parent();
if(item.is(":checked")){
relatedItem.fadeIn();
}else{
relatedItem.fadeOut();
}
}
$('input[type="checkbox"]').click(evaluate1).each(evaluate1);
</script>
The simplest approach is offcourse changing:
$('input[type="checkbox"]').click(evaluate1).each(evaluate1);
into
$('input[type="textbox"]').click(evaluate1).each(evaluate1);
But what do i need to do with:
if(item.is(":checked")){
Thanks for any help in advance.
I tried the following but it aint working.
if(item.is("M||K||H||J||V||G")){
SOLUTION BY ROBERT ROZAS
The solution is in jsfiddle
http://jsfiddle.net/dXTtz/7/
I made this code based on the code you provide:
$(document).ready(function(){
$("#periode").keyup(function(){
var valor = $("#periode").val();
$(".hidden").each(function(){
var hijo = $(this).children().attr('id');
if(hijo == valor)
{
$(this).removeClass("hidden");
}
});
});
});
Working fiddle here: http://jsfiddle.net/robertrozas/dXTtz/2/
This way is working on page load: http://jsfiddle.net/robertrozas/dXTtz/4/
Page load and removing the extra hidden divs: http://jsfiddle.net/dXTtz/5/

Categories

Resources