I would like to make the text bold by clicking a button. See below code, the problem I'm having is that I'm unable to pass the textarea ID to the boldTF() function.
<button type="button" id="tfButton">Add text</button>
<div id="InputsWrapper"></div>
<script>
$(document).ready(function() {
var tfCont = 0;
var InputsWrapper = $("#InputsWrapper");
var x = InputsWrapper.length;
var namefield = $("#tfButton");
$(namefield).click(function() {
tfCont++;
$(InputsWrapper).append('<div>' + '<div class="name" id="InputsWrapper_0' + tfCont + '">' + '<input type="textarea" id="field_' + tfCont + '" class="fTypex" placeholder="Type Here"/>' + '<br /><button type="button" onclick="boldTF("field_' + tfCont + '")">Bold</button>' + '<br>' + '</div>' + '</div>');
x++;
return false;
});
function boldTF(tmp){
document.getElementById(tmp).style.fontWeight = "bold";
//alert(tmp);
};
});
</script>
Thank you.
Remove the inline event handler and use event delegation:
$(document).on('click', 'button', function () {
$(this).closest('div.name').find('input').css('font-weight', 'bold')
})
jsFiddle example
Many issues
<input type="textarea" should be <input type="text" or <textarea ...></textarea>
Use the class to get at the field
No need to mix DOM access with jQuery
jQuery can attach event handlers on dynamically created objects using delegation.
Working fiddle
$(function () {
$("#tfButton").on("click", function(e) {
e.preventDefault;
var tfCont = InputsWrapper.length;
$("#InputsWrapper").append(
'<div class="name" id="InputsWrapper_0' + tfCont + '">' +
'<input type="text" id="field_' + tfCont + '" class="fTypex" placeholder="Your first name"/>' +
'<br /><button type="button" class="boldTF">Bold</button><br /></div>');
});
$("#InputsWrapper").on("click", ".boldTF", function(e) {
e.preventDefault();
$(this).parent().find(".fTypex").css({"font-weight":"bold"});
});
});
Related
How can I pass object to inline onclick event. When I try following code I either get undefined or [object object].
also how can I bind click event to h to avoid inline code.
this.get = function(o) {
console.log(o, o.foo);
}
this.somefunction = function(robj) {
for (var i = 0, i <= robj.length; i++) {
var fname = robj[i]['filename']
h += '<div class="checkbox checkbox-success" onclick="get(\'' + robj + '\')">' +
'<input id="' + fname + '" type="checkbox" class="styled"> ' +
'<label for="' + fname + '"><a data-fancybox-next class="button-next" href="#">' + fname + '</a></label>' +
'</div>';
}
}
A few problems I saw with your code,
your loop should be i < robj.length and has a syntax error , should be ;
h was not defined but now not used anymore
The array passed into get() cannot be accessed by using o.foo
Side note: take a look at ES6 template literals to help clean up some of the quoting action you are currently doing, for example id="' + fname + '" can look like id="${fname}"
Here is a full working example with the fixes above on how you can add a listener to your div (by creating DOM element) and with the object as a parameter.
this.get = function(o) {
console.log(o);
console.log(o.foo);
}
this.somefunction = function(robj) {
for (let i = 0; i < robj.length; i++) {
var fname = robj[i]['filename']
var myDiv = document.createElement("div");
myDiv.className = "checkbox checkbox-success";
myDiv.onclick = function(){get(robj[i])};
myDiv.innerHTML =
'<input id="' + fname + '" type="checkbox" class="styled"> ' +
'<label for="' + fname + '"><a data-fancybox-next class="button-next" href="#">' + fname + '</a></label>';
document.getElementById("container").appendChild(myDiv);
}
}
var robj = [{filename: "myFilename", foo: "myFoo"}]
somefunction(robj);
<div id="container"></div>
here is an example of dynamically written onclick . simply keep the function outside of doucment.ready
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
function changePath(distinct_inputs)
{
console.log(distinct_inputs);
}
$(document).ready(function(){
var distinct_inputs = 0;
$('.icon1').click( function(){
distinct_inputs = distinct_inputs + 1 ;
$('#insert-file').append('<ul class="ul list-inline"><li style="width:90%"><input onchange="changePath('+distinct_inputs+')" type="file" class="base'+distinct_inputs+' form-control form-input form-style-base"><input type="text" class="fake'+distinct_inputs+' form-control form-input form-style-fake" readonly placeholder="choose your file"><span class="glyphicon glyphicon-open input-place"></span></li><li class="icon fa fa-minus"></li></ul>');
});
});
</script>
</head>
<body>
<div id="insert-file" ></div>
<button type="button" class="icon1">CLick here</button>
</body>
</html>
I'm attempting to use .on() to add a text field when a dynamically created button is clicked. However, for whatever reason, I can't seem to get it working. Anyone see what's wrong? Thanks for any help and sorry if it's something obvious (I'm afraid that it might be but I just can't see it).
$('#the-basics input.typeahead').keyup(function() {
var prs = $(this).val().split(' ');
if (!$("#the-basics span.newEntityButtons").length) {
var $newEntity = $('<span class="newEntityButtons">' + '</span>');
$newEntity.appendTo($("#the-basics"));
var $newPerson = $('<input type="button" value="New Person" id="addpersonbutton" class="newHolder newPerson" />');
$newPerson.appendTo($("span.newEntityButtons"));
}
});
$('div#example').on('click', '#addpersonbutton', function() {
var epo = new Date().getTime();
var theelement = '<span class="nested-fields person">' +
'<input id="stockholder_people_attributes_' + epo + '_fname" name="stockholder[people_attributes][' + epo + '][fname]" value="' + prs[0] + '">' +
'<a class="glyphicon glyphicon-trash remove_fields existing" href="#"></a>' +
'</span>';
$('div.new_person.new_fields').prepend(theelement);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="example">
<div id="the-basics">
<input class="typeahead">
</div>
<div class="new_person new_fields">
</div>
</div>
Changes I made
► Declared variable prs as a global variable
► Remove # from the New Person button's id.
Working Demo
var prs = '';
$('#the-basics input.typeahead').keyup(function() {
prs = $(this).val().split(' ');
if (!$("#the-basics span.newEntityButtons").length) {
var $newEntity = $('<span class="newEntityButtons">' + '</span>');
$newEntity.appendTo($("#the-basics"));
var $newPerson = $('<input type="button" value="New Person" id="addpersonbutton" class="newHolder newPerson" />');
$newPerson.appendTo($("span.newEntityButtons"));
}
});
$('div#example').on('click', '#addpersonbutton', function() {
var epo = new Date().getTime();
var theelement = '<span class="nested-fields person">' +
'<input id="stockholder_people_attributes_' + epo + '_fname" name="stockholder[people_attributes][' + epo + '][fname]" value="' + prs[0] + '">' +
'<a class="glyphicon glyphicon-trash remove_fields existing" href="#"></a>' +
'</span>';
$('div.new_person.new_fields').prepend(theelement);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="example">
<div id="the-basics">
<input class="typeahead">
</div>
<div class="new_person new_fields">
</div>
</div>
Remove # from the New Person button's id.
var $newPerson = $('<input type="button" value="New Person" id="addpersonbutton" class="newHolder newPerson" />');
Declare prs outside the click event like following.
var prs;
$('#the-basics input.typeahead').keyup(function () {
prs = $(this).val().split(' ');
if (!$("#the-basics span.newEntityButtons").length) {
var $newEntity = $('<span class="newEntityButtons">' + '</span>');
$newEntity.appendTo($("#the-basics"));
var $newPerson = $('<input type="button" value="New Person" id="addpersonbutton" class="newHolder newPerson" />');
$newPerson.appendTo($("span.newEntityButtons"));
}
});
var prs = $(this).val().split(' ');
is not a global variable, and inaccessible inside $('div#example').on('click', '#addpersonbutton', function() { so duplicate it inside your second function
EDIT: to make it clear:
$('#the-basics input.typeahead').keyup(function() {
var prs = $(this).val().split(' ');
if (!$("#the-basics span.newEntityButtons").length) {
var $newEntity = $('<span class="newEntityButtons">' + '</span>');
$newEntity.appendTo($("#the-basics"));
var $newPerson = $('<input type="button" value="New Person" id="addpersonbutton" class="newHolder newPerson" />');
$newPerson.appendTo($("span.newEntityButtons"));
}
});
$('div#example').on('click', '#addpersonbutton', function() {
var prs = $(this).val().split(' ');
var epo = new Date().getTime();
var theelement = '<span class="nested-fields person">' +
'<input id="stockholder_people_attributes_' + epo + '_fname" name="stockholder[people_attributes][' + epo + '][fname]" value="' + prs[0] + '">' +
'<a class="glyphicon glyphicon-trash remove_fields existing" href="#"></a>' +
'</span>';
$('div.new_person.new_fields').prepend(theelement);
});
This is my first post so I asked for help and possible comments.
I would like to do change div (which is added by using the tool: AddR) by one position up and down when I click "onclick" with jQuery function.
I wrote something like that but it did not work ..
Could someone help me what should I improve?
Thanks for your help
<script>
function AddR(k) {
Radio_L = Radio_L + 1;
Radio_N = "Radio" + Radio_L;
$("#" + k.id + "").append("<div id='"+Radio_N+"'>" + Radio_N + "<br /><br />" +
"<button type='submit' class='button' style='float: left;' onclick='AddR(" + Radio_N + ");' >Add</button>" +
"<button type='submit' class='button' style='float: left;' onclick='UpR(" + Radio_N + ");' >Up</button>" +
"<button type='submit' class='button' style='float: left;' onclick='DownR(" + Radio_N + ");' >Down</button><br />" +
"<br />" + "<input type='text'>" + "<br /><br />" + '</div>'
);
}
function UpR(k) {
var pos = (this).index();
var parent = $("#" + k.id + "");
parent.insertAfter(pos.next());
}
function DownR(k) {
var pos = (this).index();
var parent = $("#" + k.id + "");
parent.insertBefore((pos.next());
}
</script>
I would offer a solution which simplifies the HTML, does not put in hard coded HTML in the code and uses classes rather than a lot of code embedded in the markup.
With this markup to start:
<div id='Radio_N0' class='container'><span class='containerName'>Radio_N 0</span>
<br/>
<button type='submit' class='button add'>Add</button>
<button type='submit' class='button up'>Up</button>
<button type='submit' class='button down'>Down</button>
<br/>
<input type='text' />
<br />
</div>
You could use this code to create more of these and move them around:
function AddR(k) {
Radio_L = $('.container').length;
var Radio_N = "Radio_N" + Radio_L;
var newDiv = k.parents('.container').clone();
newDiv.attr('id', Radio_N).find('.containerName').text(Radio_N);
newDiv.insertAfter(k.parents('.container'));
}
function UpR(k) {
var parent = k.parents('.container');
var pos = parent.prev();
parent.insertBefore(pos);
}
function DownR(k) {
var parent = k.parents('.container');
var pos = parent.next();
parent.insertAfter(pos);
}
$(document).on('click', '.add', function () {
AddR($(this));
});
$(document).on('click', '.up', function () {
UpR($(this));
});
$(document).on('click', '.down', function () {
DownR($(this));
});
See it in action here: http://jsfiddle.net/uka2C/
var pos = (this).index();
^---- Missing $ sign
supposed to be
var pos = $(this).index();
Also
pos with give you an number and they do not have the next method. Only jQuery objects do
Try this
function UpR(k) {
var $elem = $(this).next();
var parent = $("#" + k.id + "");
parent.insertAfter($elem);
}
Try this code (also here: http://cdpn.io/AjHyE), i've found some syntax errors:
<script>
var Kon_L = 0;
function Kon() {
Kon_L = Kon_L+ 1;
var Kon_R_N = "Kon" + Kon_L;
$("<div id='" + Kon_R_N + "' class='ka' > " + "Kon " + Kon_L +
"<button type='submit' class='button' style='float: left;' onclick='UpR(\"" + Kon_R_N + "\");' >UpDIV</button>" +
"<button type='submit' class='button' style='float: left;' onclick='DownR(\"" + Kon_R_N + "\");' >DownDIV</button>" +
"<br />Tekst<br />" +
"</div>").appendTo(".Place");
}
function UpR(k) {
var self = $("#"+k);
var prev = self.prev();
self.insertBefore(prev);
}
function DownR(k) {
var self = $("#"+k);
var next = self.next();
self.insertAfter(next);
}
</script>
Also check your browser console to see if it's working.
Anyway, since you are asking for comments i'd recommend something to you:
remove the HTML from your JS code. You could reference the buttons with some jQuery selector and move them around
remove the inline style from HTML, you can easily move the float property inside the button class
decouple the JS from the HTML even more, don't use the onclick in the HTML but use the jQuery click() function with the selectors
If you try these modifications i think that you could get more feedback from the Stack Overflow community.
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 found this javascript is called by a button
but i want it to be onload at the same time , when button click it will call this javscript as well
but i not sure how? hopefully anyone of you can help out
function AddFileUpload()
{
var div = document.createElement('DIV');
div.innerHTML = '<input id="file' + counter + '" name = "file' + counter + '" type="file" /><input id="Button' + counter + '" type="button" value="Remove" onclick = "RemoveFileUpload(this)" />';
document.getElementById("FileUploadContainer").appendChild(div);
counter++;
}
<body onload="AddFileUpload();">
You can call javascript on load using jquery.
$(document).ready(function() {
var div = document.createElement('DIV');
div.innerHTML = '';
document.getElementById("FileUploadContainer").appendChild(div);
counter++;
});