I want to display HTML content in a text box, but I am stuck.
Here is my code, which is working fine when I displayed the text into label. But its not working for text box.
HTML code:
<div id="showDiv"></div>
JavaScript code:
function myfun(){
var item="<span class="kwcat">results in <b>(.*?)</b></span>";
var div2 = document.createElement('div');
div2.setAttribute("id", "myid");
div2.setAttribute("class","inner");
value2= replaceAll(item, '<','<');
value2=replaceAll(value2, '>','>');
var comp= '<div>';
comp += '<label >';
comp += "Heading: ";
comp += '</label>';
/* comp += '<input type="text" value=' + value2 + '>'; */
comp += '<label>';
comp += value2;
comp +='</label>';
comp += '</div>';
div2.innerHTML = comp;
showDiv.appendChild(div2);
}
function replaceAll(str, find, replace) {
return str.replace(new RegExp(find, 'g'), replace);
}
The line which I have commented, is what I want to work. Where am I going wrong?
you should wrap the value in quotes
comp += '<input type="text" value="' + value2 + '">';
Wrap the input value in quotes as well
function myfun(){
var item="<span class=\"kwcat\">results in <b>(.*?)</b></span>";
var div2 = document.createElement('div');
div2.setAttribute("id", "myid");
div2.setAttribute("class","inner");
value2= replaceAll(item, '<','<');
value2=replaceAll(value2, '>','>');
var comp= '<div>'+
'<label>Heading:</label>'+
'<textarea>'+ value2 + '</textarea>'+
'<label>'+value2+'</label>'+
'</div>';
div2.innerHTML = comp;
showDiv.appendChild(div2);
}
your function should look like the above
Encode double quotes, By replacing " with "
value2=replaceAll(value2, '"','"');
Surround the value of attribute of input data type with double quotes
comp += <input type="text" value="' + value2 + '">';
Now you have your input field value as the same value of item variable
Related
I have a foreach function which listing all members of array. I want that member of array is a link which change input value.
I have function for reading input like this
<input type="text" id="syote" name="syote" value="" />
<button id="myBtn" onclick="submitti()">Submit</button>
function submitti(){
let current ="syote"
var txt = ""
let array2 = [
'soita',
'sammuta',
'google',
'listaa',
'oskari',
'tee popup',
'10',
'input alas',
'input ylös',
'värillinen',
'mustavalkoinen',
'kysely'
]
if(syote.value.toLowerCase() == "listaaa"){
document.getElementById("vas-col").className = "vasen";
array2.forEach(myFunction);
document.getElementById("result1").innerHTML = txt;
function myFunction(value, array2) {
txt = txt + "<a href=# onclick=Muuta()>" + value + "</a>" + "<br>";
}
}
function Muuta(value) {
input.value = "asdasdasd";
}
This is working and it change input value to asdasdasd.
I want it change input value same than member of array list.
I tried these without succes:
function myFunction(value, array2) {
txt = txt + "<a href=# onclick=Muuta(value)>" + value + "</a>" + "<br>";
function Muuta(value) {
input.value = value;
}
function myFunction(value, array2) {
txt = txt + "<a href=# title=value onclick=Muuta(this.title)>" + value + "</a>" + "<br>";
function Muuta(value) {
input.value = value;
}
Found some examples also and not working in my case. Like this: javascript change input value by link title
After many hours i find solution for this problem.
With this it works:
if(syote.value.toLowerCase() == "listaa"){
// Näissä kohdissa missä id:ssä on väliviiva täytyy käyttää edessä document.getElementById. Ilman sitä ei muuta classia ja näin ollen scroll ei ilmesty.
document.getElementById("vas-col").className = "vasen scroll";
array.forEach(ListaaKomennot);
result1.innerHTML = txt;
function ListaaKomennot(value, array) {
txt = txt + "<a href='#' title='" + value + "' onclick='MuutaArvo(this.title);'>" + value + "</a>" + "<br>";
}
}
function MuutaArvo(arvo) {
syote.value = arvo;
}
In title is very important to be ' before " and same vice versa after value. Without ' ' it cuts out after whitespace when change value of input to title. If you have only words without whitespace that is not a problem.
It is best to solve yourself, i learned many new things at same time. Inter alia if your html id name is with - tag like i have in oik-col you must use document.getElementById without it, className won't work.
Here I attach the images where you can see the list of data which show after page load but in all rows but when i add the row using jquery it is not show the data. please check image 2
image first
image 2
This is the link of mtree demo and this is the codepen link
and below is the code that i use to generate row and display mtree.
$(document).ready(function() {
var ite = <?php echo $projectCount; ?>;
$('.btn-row-add').click(function() {
var leaveDays = checkLeaveDays();
console.log(leaveDays);
var ite2 = 1
style = '';
readOnly = '';
if(jQuery.inArray(ite2, leaveDays) !== -1){
style = "style = 'background:#00FF00;'";
readOnly = "readonly='readonly'";
}
var el2 = '<td><input '+style+' '+readOnly+' id="text_'+ite2+'" class="short-textbox" type="text" name="day_'+ite+'[]" value="" onkeyup="sumNewRows(), colsValues(), colsVertical()"></td>';
for(var i=2; i<<?php echo $noOfDays+1; ?>; i++) {
styleInner = '';
readOnlyInner = '';
if(jQuery.inArray(i, leaveDays) !== -1){
styleInner = "style = 'background:#00FF00;'";
readOnlyInner = "readonly='readonly'";
}
el2 = el2 + '<td><input '+styleInner+' '+readOnlyInner+' id="text_'+i+'" class="short-textbox" type="text" name="day_'+ite+'[]" value="" onkeyup="sumNewRows(), colsValues(), colsVertical()"></td>';
}
console.log($('whc-table tbody').html());
var el = '<tr id="data_'+ite+'">\n' +
'<th scope="row">\n' +
'<select class="dropdownlist" data-text-field="name" name="project_name[]" style="width: 300px;">\n' +
'<option value=""></option>\n' +
'</select>\n' +
'\n' +
'</th>\n' +
'<td id="mm-transit">\n' +
'\n' +
'<div class="fake-input">\n' +
'<input value="" name="task_no[]" class="task_list" id="task_list_" type="text" title="Show category list here leter"><img class="show_task" id="show_task" src="<?=base_url()?>images/down.png">\n' +
'\t<div id="cat-list-" class="cat-list"><?php echo $categories_list ?></div>\n' +
'</div>\n' +
'</td>\n' +
el2 +
'\n' +
'<td style="text-align: center;">\n' +
'<input style="width: 35px;" id="text_total_'+ite+'" readonly=\'readonly\' class="short-textbox" type="text" name="total_'+ite+'" value="">\n' +
'</td>\n' +
'</tr>';
ite++;
$(el).appendTo($('#whc-table tbody'));
projectDropdown();
taskDropdown();
initializeMtree();
});
});
Note - same way i used to show mtree in normal rows means rows those are not generated by javascript that is
Try using
$('.btn-row-add').on('click', function() {
instead of
$('.btn-row-add').click(function() {
I have a string as below
var a = "M=1234&b=sdaks&c=sdkssad&strXML=<a><b mode="abc"><c>string content</c></b></a>"
Then I split it with &
var b = a.split('&');
Then further more I split b with = in loop and append to the form
$.each(b, function (index) {
var paramsV = b[index].split('=');
frm.append('<input type="hidden" name="' + paramsV[0] + '" value="' + paramsV[1] + '" /> ');
});
But when it split with = that time it is splitting result string which have = inside the string and it is splitting that too. I would like to know how I can stop splitting the result string.
I this what you want to achieve, Use .split(/=(.+)/) to only split the first =
Also notice that when you try to enter paramsV[1] that has a " inside it, it will break the original code of Input, that's why I replaces it with .replace(/\"/g, "''")
var a = 'M=1234&b=sdaks&c=sdkssad&strXML=<a><b mode="abc"><c>string content</c></b></a>'
var b = a.split('&');
var frm = $(".frm")
$.each(b, function(index) {
var paramsV = b[index].split(/=(.+)/);
frm.append('<input type="" name="' + paramsV[0] + '" value="' + paramsV[1].replace(/\"/g, "''") + '" /> ');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="frm"></div>
You have made a mistake in variable declaration. Inside double quotes you need to use single quotes. And you need to use regular expression like .split(/=(.+)?/). See the output below.
$(function(){
var a = "M=1234&b=sdaks&c=sdkssad&strXML=<a><b mode='abc'><c>string content</c></b></a>";
var b = a.split('&');
$.each(b, function (index) {
var paramsV = b[index].split(/=(.+)?/);
console.log('<input type="hidden" name="' + paramsV[0] + '" value="' + paramsV[1] + '" /> ');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
var a = "M=1234&b=sdaks&c=sdkssad&strXML=<a><b mode='abc'><c>string content</c></b></a>";
var b = a.split('&');
$.each(b, function (index) {
var index1 = b[index].indexOf("=")
var markup ='<input type="hidden" name="' + b[index].substring(0, index1) + '" value="' + b[index].substring(index1) + '" /> ';
console.log(markup);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
Check it
I have some code which uses this to allow to keep the same function code but apply it to different form elements which can be seen on a jsFiddle demo
//latest
var maxFields = 10,
currentFields = 1;
$('.form').on('click', '.add', function () {
var value_src = $(this).prev();
var container = $(this).parent().prev();
if ($.trim(value_src.val()) != '') {
if (currentFields < maxFields) {
var value = value_src.val();
var html = '<div class="line">' +
'<input id="accepted" type="text" value="' + value + '" />' +
'<input type="button" value="X" class="remove" />' +
'</div>';
$(html).appendTo(container);
value_src.val('');
currentFields++;
} else {
alert("You tried to add a field when there are already " + maxFields);
}
} else {
alert("You didn't enter anything");
}
})
.on('click', '.remove', function () {
$(this).parents('.line').remove();
currentFields--;
});
My issue is that I still want to be able to limit each section to only have 10 <inputs>, but at the moment each section shares the counter, so 5 in requirements and 5 in qualifications would trigger the 10 limit.
Is there a nice clean way of keeping the input field counter separate for each section?
What you need to do is store the current number of children for each list in a context sensitive way. There are a couple ways you could structure this (it would be easy using MVC libraries or the likes), but the simplest solution for your code will be to just use the DOM. So instead of using your global currentFields variable, instead use container.children().length to get the number of notes in the list you are currently operating on.
http://jsfiddle.net/9sX6X/70/
//latest
var maxFields = 10;
$('.form').on('click', '.add', function () {
var value_src = $(this).prev();
var container = $(this).parent().prev();
if ($.trim(value_src.val()) != '') {
if (container.children().length < maxFields) {
var value = value_src.val();
var html = '<div class="line">' +
'<input id="accepted" type="text" value="' + value + '" />' +
'<input type="button" value="X" class="remove" />' +
'</div>';
$(html).appendTo(container);
value_src.val('');
} else {
alert("You tried to add a field when there are already " + maxFields);
}
} else {
alert("You didn't enter anything");
}
})
.on('click', '.remove', function () {
$(this).parents('.line').remove();
});
You can add a class to each row like form-row
var html = '<div class="line form-row">' +
'<input id="accepted" type="text" value="' + value + '" />' +
'<input type="button" value="X" class="remove" />' +
'</div>';
and count the length by using
console.log($(container).find('.form-row').length);
// Use +1 because initially it is 0
Fiddle http://jsfiddle.net/9sX6X/69/
You can make use of the placeholder property to identify which button triggered the function.
value_src.attr('placeholder');
This string can then be used to access three different counters in an associative array.
Code
var maxFields = 10;
var currentFields = new Object;
$('.form').on('click', '.add', function () {
var value_src = $(this).prev();
var container = $(this).parent().prev();
if ($.trim(value_src.val()) != '') {
var identity = value_src.attr('placeholder');
if(currentFields[identity] == undefined)
currentFields[identity] = 0;
if (currentFields[identity] < maxFields) {
var value = value_src.val();
var html = '<div class="line">' +
'<input id="accepted" type="text" value="' + value + '" />' +
'<input type="button" value="X" class="remove" />' +
'</div>';
$(html).appendTo(container);
value_src.val('');
currentFields[identity]++;
} else {
alert("You tried to add a field when there are already " + maxFields);
}
} else {
alert("You didn't enter anything");
}
})
.on('click', '.remove', function () {
$(this).parents('.line').remove();
currentFields--;
});
JSFiddle: http://jsfiddle.net/9sX6X/73/
I creating jquery code to generate specific html-blocks that contains html-controls (e.g. textbox, textarea, button) with two buttons - add new block and delete current block:
$(document).ready(function () {
// Constants
var SEPARATOR = "`";
var SEPARATOR_START = "<span class='Hidden'>";
var SEPARATOR_END = "</span>";
var SEPARATOR_BLOCK = SEPARATOR_START + SEPARATOR + SEPARATOR_END;
var CONTAINER = "#weContainer";
// Initialize container
InitializeDataContainer(CONTAINER);
// Buttons events
$(".AddBlock").click(function () {
AddBlock(CONTAINER);
});
$(".DeleteBlock").click(function () {
DeleteBlock(CONTAINER, GetParentId(this));
});
// Functions
function GetParentId(container) {
var id = ($(container).parent().attr("id")).replace(new RegExp("_", 'g'), "");
return id;
}
function Template() {
var uniqueId = Math.random() * 10000000;
var template = "<div class='weBlock' id='_" + uniqueId + "_'>";
template += "<input type='button' value='add' class=\"AddBlock\" />";
template += "<input type='button' value='del' class=\"DeleteBlock\" />";
template += "<br/>";
template += "<input type='text' class='weStartDate weTextbox' />";
template += " ";
template += "<input type='text' class='weEndDate weTextbox' />";
template += "<br/>";
template += "<input type='text' class='weCompany weTextbox' />";
template += " ";
template += "<input type='text' class='weJobTitle weTextbox' />";
template += "<br/>";
template += "<input type='text' class='weClients weTextbox' />";
template += " ";
template += "<input type='text' class='weProjectName weTextbox' />";
template += "<br/>";
template += "<textarea type='text' rows='4' cols='40' class='weProjectDesc weTextarea'></textarea>";
template += "<br/>";
template += "<textarea type='text' rows='6' cols='40' class='weActivities weTextarea'></textarea>";
template += "<br/>";
template += "<textarea type='text' rows='4' cols='40' class='weToolsTech weTextarea'></textarea>";
template += "</div>";
template += SEPARATOR_BLOCK;
return template;
}
function GetIdFromTemplate(template) {
var array = template.split('_');
return array[1];
}
function AddBlock(container) {
$(container).append(Template());
}
function DeleteBlock(container, id) {
var content = $(container).html();
content = content.replace(new RegExp("\<span class='Hidden'\>", "g"), "")
.replace(new RegExp("\</span\>", "g"), "");
var blocks = content.split(SEPARATOR);
content = "";
var index;
for (var i = 0; i < blocks.length; i++) {
if (GetIdFromTemplate(blocks[i]) != id && !IsNullOrEmpty(blocks[i])) {
content += blocks[i] + SEPARATOR_BLOCK;
}
else {
index = i;
}
}
$(container).html(content);
}
function IsNullOrEmpty(string) {
if (string == null || string == 'undefined' || string.length == 0) {
return true;
}
else {
return false;
}
}
function InitializeDataContainer(container) {
$(container).html(Template());
}
});
For the first time (when page load) i created first block:
function InitializeDataContainer(container) {
$(container).html(Template());
}
My problem is next - buttons Add and Delete work only for this first html-block that i created when page load, but if i add new blocks in page using Add button (from this first block that works) then buttons Add and Delete from this new blocks doesn't work!
Sorry for may be not good code, im not javascript engineer:)
Use the .live() instead:
$(".AddBlock").live("click", function () {
AddBlock(CONTAINER);
});
And same for the other class - the .click() is "static" only for the elements that exists in the time of calling it, while .live() should work for any existing or future elements.
Your jQuery code adds event handlers to the Add/Delete buttons you create uses click to do so:
$(".AddBlock").click(function () {
AddBlock(CONTAINER);
});
This only affects HTML elements that are already in the page.
One solution would be to change it to
$(".AddBlock").live('click', function () {
AddBlock(CONTAINER);
});
to make it also work for elements that get added to the page later.
Another solution would be to manually add the click event handlers to any elements you add to the page dynamically:
function AddBlock(container) {
var $template = $(Template());
$(container).append($template);
$template.find(".AddBlock").click, function () {
AddBlock(CONTAINER);
});
$template.find(".DeleteBlock").click, function () {
DeleteBlock(CONTAINER, GetParentId(this));
});
}