I'm Having a bit of an issue. I'm using JavaScript to inset HTML into a webpage along with an event handler for the onblur event. It looks like this:
return '<input id = "txtIn" type="text" value=" ' + dateTime + '" onblur= "submitManualDate(document.getElementById("txIn").value(), 2, 3);" />';
I'm getting a syntax error. However, the following works perfectly fine:
return '<input id = "txtIn" type="text" value=" ' + dateTime + '" onblur= "submitManualDate(1, 2, 3);" />';
Any idea what I'm missing?
Using " inside "(double quoted) expression will break the string.
It's better to pass this as an argument as you should not have multiple elements with same id attributes in a document.
Try this example:
(function() {
var input = '<input type="text" value="5" onblur= "submitManualDate(this, 2, 3);" />';
document.getElementById('parent').innerHTML = input;
})();
function submitManualDate(elem, j, k) {
alert(elem.value + ' ' + j + ' ' + k);
}
<div id='parent'></div>
Fiddle here
Related
In my javascript code, i am able to output the id of a the selected item. I want to pass the id to my controller. I appended the input(created in the JS code) to my html form so as to get the id of the selected item but it wouldn't do the trick.
*HTML**
<form>
// inputs for form in here
</form>
JS
$(".myItem").append(
'<p name="item_id" id="item_id">Item ID: ' + item.id + '</p>').appendTo('form');
Controller
$getID = Input::get('item_id');
$fetchItem = Item::all()->where('id',$getID)->first();
Try to append an input element instead of a p:
$(".myItem").append(
'<input name="item_id" id="item_id" value=' + item.id + ' />).appendTo('form');
You can even have both; 1 to store the value (input) and the other to show it on screen (p).
$(".myItem").append('
<input type="hidden" name="item_id" id="item_id" value=' + item.id + ' />
<p>Item ID: ' + item.id + '</p>').appendTo('form');
So this is what the page looks like currently:
The first one is hardcoded in and then the rest are added/removed by the buttons. The first one can also be added and removed from the buttons. I want to call a jquery function when the dropdown is changed to change the type from textbox/radiobutton (and text)/checkbox (and text) etc.
Currently it only works on the first Question/Answer and only works if it is the original and not dynamically created. I'm not sure why that is.
Here is how the Q/A's are created and removed
$("#addButton").click(function () {
if (counter > max_fields) {
alert("Only " + max_fields + " Questions allowed");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Question #' + counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="questionbox' + counter + '" value="" />' +
' <select id="choice'+ counter +'"><option>Type</option><option>Radio Button</option><option>Text Box</option><option>Check Box</option></select>' +
'<button id = "remove' + counter + '">Remove</button>' +
'<br/><label>Answer #' + counter + ' : </label>' +
'<div id="Answers' + counter + '">' +
'Option 1: <input type="text" id="answerbox' + counter +
'1" name="answerbox' + counter + '" value="" />' +
'<br/>Option 2: <input type="text" id="answerbox' + counter +
'2" name="answerbox' + counter + '" value="" />' +
'<br/>Option 3: <input type="text" id="answerbox' + counter +
'3" name="answerbox' + counter + '" value="" />' +
'<br/>Option 4: <input type="text" id="answerbox' + counter +
'4" name="answerbox' + counter + '" value="" /></div>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if (counter == 1) {
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
This is how I tried to get it to change types
$('#choice1').change(function () {
var selected_item = $(this).val()
var searchEles = document.getElementById("Answers1").children;
alert(searchEles.length);
for(var i = 0; i < searchEles.length; i++) {
$('#answerbox1' + i).attr('type', selected_item);
//alert(searchEles.length);
}
});
The web page code is as follows
<input type='button' value='Add Question' id='addButton'/>
<input type='button' value='Remove Question' id='removeButton'/>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Question #1 : </label>
<input type='text' id='questionbox1'/>
<select id="choice1" onchange="$('#choice').val('id');"> //this on change was added and currently does nothing it seems.
<option value="">Type</option>
<option value="radio">Radio Button</option>
<option value="text">Text Box</option>
<option value="checkbox">Check Box</option>
</select>
<button id="remove1">Remove</button>
<br/><label>Answer #1 : </label>
<div id="Answers1">
Option 1: <input type="text" id='answerbox11' name='answerbox1' value="" />
<br/>Option 2: <input type="text" id='answerbox12' name='answerbox1' value="" />
<br/>Option 3: <input type="text" id='answerbox13' name='answerbox1' value="" />
<br/>Option 4: <input type="text" id='answerbox14' name='answerbox1' value="" />
</div>
</div>
</div>
I tried to do something like onchange and then get the ID and go from there but that didn't work. I know it doesn't match the back end jquery name.
TL;DR
I don't know how to dynamically write the jQuery function to work
for all of them.
I don't know why even if I hardcode it to #choice1 it will work
when its first created but not if i remove and add it even though it
has the same exact values. I think it might MAYBE have to do with
for loop, because the alert doesn't even trigger the second time
around.
You could try
$(document).on("change", ".selector", function(){
//do something
});
//Edit
Add to the select element class for example select-option and a tag that will hold the select's counter
//JS
...'<select id="choice'+counter+'" class="select-option" number="'+counter+'">'...
and then your on change function would look something like
$(document).on("change", ".select-option", function(){
//do something
var selected_type = $(this).attr('value');
var ans_number = $(this).attr('number');
$("#answerbox"+ans_number).children('input').attr('type', selected_type);
});
I hope this will help :)
For dynamically added elements use
$(selector).on("change", callback)
If element is dynamic then Jquery will not bind directly as
$('#choice1').change(function (){});
But for that you need to call same function with some static element.
For Ex:
$(".listingDiv").find('#choice1').change(function (){});
or
$(document).find('#choice1').change(function (){});
and it will work. try it.
When elements will be aded dynamically, best practice is to delegate the handler(s). Put your handler on the containing div or window/document
.
First
<select id="choice1" onchange="$('#choice').val('id');"> //this on change was added and currently does nothing it seems.
This is one reason your never be called. If you bind an event listener to an element, you should not write the actual JS code inside the element.
Second
Bind your listener like this:
$('#choice1').on("change", function () {
var selected_item = $(this).val()
var searchEles = document.getElementById("Answers1").children;
alert(searchEles.length);
for(var i = 0; i < searchEles.length; i++) {
$('#answerbox1' + i).attr('type', selected_item);
//alert(searchEles.length);
}
});
I'm trying to get the value of a selected radio button with jQuery. I generate my html-elements with jquery from a json-template, this is my code for generating radio buttons:
function AddRadio(labelName, buttons, i, paneIndex, dataID) {
$('#Ctabs1-pane' + paneIndex + '').append('<div class="form-group"><label class="col-lg-2 control-label">' + labelName + '</label><div class="col-lg-10" id="' + dataID + '"></div></div>');
$.each(buttons, function (j, value) {
$('#' + dataID).append('<div class="radio"><label><input type="radio" name="optionsRadios" value="' + value + '">' + value + '</label></div>');
});
}
i try to get the selected radiobutton with this code:
return $("input[type='radio'].radioBtnClass:checked").val();
But this gives me undefined
What am i doing wrong?
Your selector match input element with class radioBtnClass but you're not added it when append. Either add that class into your input:
$('#' + dataID).append('<div class="radio"><label><input type="radio" class="radioBtnClass" name="optionsRadios" value="' + value + '">' + value + '</label></div>');
or target it by name instead:
$("input[type='radio'][name='optionsRadios']:checked").val();
Please check the JSFIDDLE , the rel attribute in the alert comes out as 'undefined' :
var ItemTypeArray = $('input[name^=ItemType]:checked').map(function(){
alert(this.id + ' , r= ' + this.rel);
return this.rel + '--' + this.value;
}).get().join(",");
Also , this function gives a string , but I need an array to be constructed to post it.
There's no such attribute called rel on an input (there is on a link tag however). You should really use data attributes instead:
<input id="SOLD[1]" value="1" name="ItemType[1]" type="radio" data-rel="1">
<input id="PURCHASED[1]" value="2" name="ItemType[1]" type="radio" checked="checked" data-rel="1">
Then you can do:
var ItemTypeArray = $('input[name^=ItemType]:checked').map(function () {
alert(this.id + ' , r= ' + $(this).data("rel"));
return $(this).data("rel") + '--' + this.value;
}).get().join(",");
Or to return what you stated in comments (an array), you can do:
var ItemTypeArray = [];
$('input[name^=ItemType]:checked').each(function () {
ItemTypeArray.push(this.id + ' = ' + $(this).data("rel"));
});
See HERE
I just included jquery and modified your code as follows. Use $(this).attr('rel') instead of this.rel
var ItemTypeArray = $('input[name^=ItemType]:checked').map(function () {
alert(this.id + ' , r= ' + $(this).attr('rel'));
return this.rel + '--' + this.value;
}).get().join(",");
Here is the jsfiddle
try
$(this).attr("rel")
this will get you an attribute value named 'rel'
I have this JavaScript that adds a form field, along with a link to remove that field:
var fieldCount = 0;
function addField() {
var name = 'file' + fieldCount;
var row = 'row' + fieldCount;
var str = '<p id="' + row + '"><label for="' + name + '">File to upload: <input type="file" name="' + name + '" id="' + name + '" />(100MB max size) <a onclick="removeRow(' + row + '); return false;">[-]</a></label></p>';
fieldCount++;
$("#fields").append(str);
};
function removeRow(id) {
$(id).remove();
};
Here is the markup:
<form id="ajaxUploadForm" action="<%= Url.Action("AjaxUpload", "Upload")%>" method="post" enctype="multipart/form-data">
<fieldset id="uploadFields">
<legend>Upload a file</legend>
<div id="fields"></div>
<input id="ajaxUploadButton" type="submit" value="Submit" />
</fieldset>
<a onclick="addField(); return false;" id="add">Add</a>
<div id="resultBox">
<p id="status" style="margin:10px;"></p>
</div>
</form>
The addFields works as expected, but when I click the remove link firebug tells me that row# is not defined, where # is any number of the added fields.
Any help would be appreciated!
You need to pass a valid selector expression for an ID selector (#ID), either in the removeRow call (also note the quotes surrounding the ID selector):
'<a onclick="removeRow(\'#' + row + '\'); return false;">'
Or in the removeRow function itself:
function removeRow(id) {
$("#" + id).remove();
};
You need to have quotes around it, since it's a string.
You also need the "#" to make it into a selector:
var str = '... <a onclick="removeRow(\'#' + row + '\'); return false;">...';
A better way would be to assign the onclick as a function (not sure of the jQuery way to do this but in plain Javascript):
var a = document.createElement('a');
a.onclick = (function(row)
{
return function()
{
removeRow(row);
return false;
};
})();
You are passing in the string value of row12, but the selector should be:
$('#'+row).remove()
The # specifies that you are looking for an ID. I agree with what I think one of the other answers was about to say, you should just use the onclick events natural this keyword instead:
<p onclick="remove(this)">something</p>
function remove(what) {
$(what).remove()
}
Or, maybe just forget the whole thing all together and switch to behavior for those kinds of rows:
$('.removableRow').live('click', function() {$(this).remove()});
Then you just specify that the row is removable, and never have to worry about binding events at all:
<p><a class="removableRow" href="#">Remove</a></p>