javascript html label displaying incorrect values - javascript

I have a string that coming from a database something like this test (test<sup>®</sup>) that I would like to display in a label. I try to parse the text but it displays just the last value in the string. I did try to set the innerHTML value to the string and that didn't display any value.
Is there any other way to fix this?
strHTML = $.parseHTML('test (test<sup>®</sup>)');
var Name = "";
$.each(strHTML, function (i, el) {
Name = el.wholeText;
});
$(".lbl-drug").text(Name);

strHTML = $.parseHTML('test (test<sup>®</sup>)');
$(".lbl-drug").html(strHTML);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="lbl-drug"></label>

Related

Uncaught TypeError: Cannot set property 'value' of null after the page loads

I know this has been asked so many times, but i couldn't find the answer for my scenerio. Below is my code. I'm getting this error in the last line inside findPattern function. But i have that ID created inside createMyArea as textArea += 'id="P'+app_page_id+'_VALUE'+key+'". But why this is not finding the ID? Please let me know what i'm doing wrong here. I'm loading this after the page loads
var app_page_id = 40;
var app_pattern_page_id = 32;
var app_id;
var checksum;
var lang;
$(document).ready(function() {
app_id = $("#pFlowId").val();
checksum = $("#pInstance").val();
createMyFlow();
function createMyFlow(){
var result = new htmldb_Get(null, $v('pFlowId'), 'APPLICATION_PROCESS='+getAllLanguagesProc, $v('pFlowStepId'));
lang = jQuery.parseJSON(result.get()).lang;
createMyArea();
result = loadDataFromMyOra();
if(result !== null)
findPattern(result);
}
function createMyArea(){
var textArea;
for ( var key in lang){
textArea = '<tr><td align="right"><label for="P'+app_page_id+'_VALUE_'+key+'">';
textArea += '<span class="optional">Name '+languages[key][0]+': </span></label></td>';
textArea += '<td align="left" valign="middle">';
textArea += '<input type="hidden" name="p_arg_names" />';
textArea += '<fieldset id="P'+app_page_id+'_VALUE_fieldset_'+key+'" class="textarea" tabindex="-1">';
textArea += '<input name="p_t04" type="text" maxlength="50" size="32" value=""';
textArea += 'id="P'+app_page_id+'_VALUE'+key+'" required="" class="text_field"></fieldset>'
textArea += '</td></tr>';
$('.formlayout').append(textArea);
}
}
function findPattern(patterns)
{
var item = "";
for ( var key in patterns){
item = patterns[key]+"";
item = item.replace(/,/g,",");
item = item.replace(/“/g,'"')
document.getElementById("P"+app_page_id+"_VALUE"+key).value = item; //error here
}
}
});
The error indicates document.getElementById("P"+app_page_id+"_VALUE"+key) is null. Work backwards and think of all the reasons it might be null:
What does "P"+app_page_id+"_VALUE"+key evaluate to? Does an element with this id exist in the DOM? (You can manually inspect the DOM tree with browser dev tools, or try running getElementById() in the dev console.)
An element with that id probably doesn't exist. You point out you are trying to create it, but is there any reason that createMyArea() might not be working?
If lang is an empty object, this loop will execute 0 times: for (var key in lang) ...
The for loop iterates on keys of the lang object, but inside the loop you access via languages[key]. That is a little weird.
Their are many more things to check, but this should give you an idea of things to look for. Work backwards and test all your assumptions!
Have you checked the generated HTML or is it impossible to provide such example?
Also I've noticed that you use var way more than you should for your variables. Have a quick read about when to use what here or here.
The function that generates the code createMyArea() uses the keys in the lang variable
for ( var key in lang){
....
textArea += 'id="P'+app_page_id+'_VALUE'+key+'" required="" class="text_field"></fieldset>'
....
but in the findPatterns you are checking the id of the document using keys from another variable
for ( var key in patterns){
....
document.getElementById("P"+app_page_id+"_VALUE"+key).value = item;
....
If the patterns variable and lang variable don't have the same key, then you will get an error.
To check that, you can
console.log ("P'+app_page_id+'_VALUE'+key+'")
just before the document.getElementById and see what values is checked there.

javascript/jquery mutate and append html in var

I got a simple array like this:
var arr = ['string_1', 'string_2'];
And I got the following html (simplified, but original is very large):
var html = '<div><input class="myInput" type="text"></div>'
I need to append to #main_div in my DOM this html variable, but filled with values from arr, so in this case there should be 2 inputs, filled with string_1 and string_2.
I tried the following code:
$.each(arr, function(k, v){
$(html).find('.myInput').val(v);
$('#main_div').append(html);//mutated html var should be here
});
but I get 2 empty inputs. Any ideas how to fix it would be welcome. Thank you
Your logic is almost there, but the problem is that you're not storing the jQuery object that you create from the html string, so you just append the unchanged original value. Try this:
var arr = ['string_1', 'string_2'];
var html = '<div><input class="myInput" type="text"></div>'
$.each(arr, function(i, v) {
var $html = $(html).find('.myInput').val(v).end();
$('#main_div').append($html);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main_div"></div>
Note the use of end() which returns the originally selected element (the outer div from the html string in this case) instead of the .myInput element resulting from the find() call.
Finally, you need to give the input elements name attributes to ensure they are still valid HTML.

Javascript variable cut off after apostrophe

I have a Javascript which reads the text from two HTML drop-down lists, removes all special characters, and then stores the text in a variable. The text in the drop-down lists are coming from a JSON file. The problem is that whenever the text from the drop-down lists has an apostrophe, the Javascript cuts the string at the apostrophe, hence all text after the apostrophe is not included in the Javascript variable.
I have included a replace rule to try and replace all apostrophes with a non-space, but no luck. I cannot avoid the problem by using HEX codes, since the Javascript reads text directly from the HTML drop-down lists.
Example: If a user selects "Belgium" and "Braine-l'Allerud" in the drop-down lists, the javascript should create a variable "Cities-belgium-brainelallerud.html". Instead, it cuts all text after the apostrophe in "Braine-l'Allerud" and instead creates a variable "Cities-belgium-brainel.html"
Here is the JSON file (basis for the text in drop-down lists):
"austria": "Hirschegg,Salzburg,Bergheim,Wien",
"belgium": "Antwerpen,Braine-l'Alleud,Brugge"
And here is the Javascript code:
jQuery( "button[type='submit']" ).click(function(e) {
e.preventDefault()
var var1 = $('#json-one').val()
var var2 = $('#json-two').val().toLowerCase().replace(/'/g,"").replace(/[^a-zA-Z0-9_-]/g,'')
var link = "Cities-"+var1+"-"+var2+".html"
console.log(link)
document.location = link;
});
The JSON values are extracted into the drop down lists by the following script:
$(document).ready(function(){
$("#json-one").change(function() {
var $dropdown = $(this);
$.getJSON("../jsondata/data003.json", function(data) {
var key = $dropdown.val();
var vals = [];
switch(key) {
case 'austria':
vals = data.austria.split(",");
break;
case 'belgium':
vals = data.belgium.split(",");
break;
}
var $jsontwo = $("#json-two");
$jsontwo.empty();
$.each(vals, function(index, value) {
$jsontwo.append("<option value='"+value+"'>" + value + "</option>");
});
});
});
$("#json-one").trigger('change');
});
The drop-down list is dynamic; the 2nd drop down list (cities) is dependent on what the user chooses in the 1st drop down list (countries).
Finally, the drop down list is written as follows in the HTML:
<span class="fontyellow">Country:</span>
<select id="json-one">
<option value="austria">Austria</option>
<option value="belgium">Belgium</option>
</select>
<span class="fontyellow">City:</span>
<select id="json-two">
</select>
Thanks in advance.
Ok, the problem is in your dynamic construction of the options. You have organized your apostrophes in this manner:
$jsontwo.append("<option value='"+value+"'>" + value + "</option>");
As a result, the single quote is surrounding the city name in the 'value' portion of this string and hence the string is cutoff at the first single apostrophe it runs into. Basically it looks like this when constructed:
<option value='Braine-l'Alleud'>Braine-l'Alleud</option>
You need to use double quotes for that portion of the string instead:
$jsontwo.append('<option value="'+value+'">' + value + "</option>");
That will fix the problem and give you the following:
<option value="Braine-l'Alleud">Braine-l'Alleud</option>
I am not sure why you are generating the link the way you are but if you replace the code from jQuery to javascript, it should be able to read the text.
Like below:
var var1 = document.getElementById("json-one").innerText;
var var2 = document.getElementById("json-two").innerText;
I put the html in div like below:
<div id="json-one">Hirschegg,Salzburg,Bergheim,Wien</div>
<div id="json-two">Antwerpen,Braine-l'Alleud,Brugge</div>
OR
replace .val() to .html() like below:
var var1 = $('#json-one').html();
var var2 = $('#json-two').html();
See if it helps!

How can i get my string replace with to equal the value of a form input?

Im trying to use string replace to change a line of code within my page.
<script type="text/javascript">
function replaceScript() {
var toReplace = 'LINE OF CODE 333';
var replaceWith ='??????????';
document.body.innerHTML = document.body.innerHTML.replace(toReplace, replaceWith);
}
</script>
How can I get my...
var replaceWith ='??????????';
...to equal the value of an input from a form on the page?
Note the input value is auto populated on page load and the user does not enter in there own email address.
I assume you have an input such as <input id="inputValue" type="text" />
The general approach is to use a DOM function like getElementById() or querySelector(), and access its value with the value property.
Your code could be as simple as:
<script type="text/javascript">
function replaceScript() {
var toReplace = 'LINE OF CODE 333';
var replaceWith = document.getElementById('inputValue').value;
document.body.innerHTML = document.body.innerHTML.replace(toReplace, replaceWith);
}
</script>

Dynamically loaded form won't update correctly

I have a form which is loaded into the page using .load(). I want to update the form with the HTML I compute in str, but my code isn't updating the form correctly. Why?
if($(this).is('.step3')){
//Splits the comma seperated values into input fields
var active_fields = ($('#templateFields').val()).split(',');
$('#loadedcontent').load('template.html #step3',function(){
$('#steps').text('Step Three');
$('#start.btn').text('Save Template & Values').removeClass('step3').addClass('step4');
});
str = "";
for(var i = 0; i<active_fields.length; i++){
str += '<label>'+active_fields[i]+'</label><input name="'+active_fields[i]+'" type="text" class="span3">';
}
$('form#values.well').html(str);
}
You have to put the form modification in the load completion function like this:
if($(this).is('.step3')){
//Splits the comma seperated values into input fields
var active_fields = ($('#templateFields').val()).split(',');
$('#loadedcontent').load('template.html #step3',function(){
$('#steps').text('Step Three');
$('#start.btn').text('Save Template & Values').removeClass('step3').addClass('step4');
str = "";
for(var i = 0; i<active_fields.length; i++){
str += '<label>'+active_fields[i]+'</label><input name="'+active_fields[i]+'" type="text" class="span3">';
}
$('form#values.well').html(str);
});
}
The way you were doing it, your code to modify the form was running before the form finished loading so it wouldn't find the content and thus couldn't modify it.
Sorry, I figured i couldnt nest a form within a form. I think thats why it didnt work

Categories

Resources