I am using a WordPress module abase to get some data from database and send them to a form. The problem is, that abase form does not allow to use select input. Because of that I am trying to convert text input to a select. I created function toSelect, to which I pass id of element and list of options (for testing I put id of element to function definition).
function toSelect(itemid,valuelist) {
var out = '';
out += '<select id="bus311mtd_2_status" style="width:50px;">';
for (i=0; i < valuelist.length; i++) {
out += '<option value="'+valuelist[i]+'">'+valuelist[i]+'</option>';
}
out += '</select>';
alert(out);
$("#bus311mtd_2_status").replaceWith(out);
//$("#bus311mtd_2_status").replaceWith('<input type="text" value="zamontowane">');
}
alert(out) gives nice select input code, but $("#bus311mtd_2_status").replaceWith(out) does not work.
Even something like: $("#bus311mtd_2_status").replaceWith('<input type="text" value="zamontowane">') doesn't work.
Element with id bus311mtd_2_status for sure exists (i.e. changing its value using document.getElementById() works fine)
Maybe jQuery doesn't work?
Your code seems to work fine for me. Perhaps it's your function call. I used:
toSelect(null, ['a', 'b', 'c']);
itemid doesn't appear to be used in the function.
Here's a fiddle with your code working:
http://jsfiddle.net/dgrundel/Lko6aftf/
Here's a slightly optimized version of the function, that uses the itemid argument:
function toSelect2(itemid,valuelist) {
var html = '<select id="' + itemid + '" style="width:50px;"><option>' +
valuelist.join('</option><option>') +
'</option></select>';
$('#' + itemid).replaceWith(html);
}
toSelect2('myInput2', ['d', 'e', 'f']);
Thank you for the answer and optimization. I used itemid initially but because of problems I temporarily replaced it with id of some existing element to make sure that the problem is somwhere else.
All the code until first alert works fine and alert(out) gives the popup window with text:
<select id="bus311mtd_2_status" style="width:50px;"><option value="ready">ready</option><option value="awaiting">awaiting</option></select>
This works as was expected. But the problem starts with the next line.
I wanted to show that even such an easy code like below doesn't work.
$("#bus311mtd_2_status").replaceWith('<input type="text" value="zamontowane">');
So it looks like the jQuery was not supported.
And I've got another observation: within script tags no empty lines are allowed (the code doesn't work if they are present).
Related
I'm using a button to dynamically generate a new table row in my form and the lines include calling functions with parameters. I tried using JQuery on the added lines to trigger the .blur() event, as was successfully done with the hardcoded first table row, but the page completely ignored it. So I'm trying another route of triggering the onblur() event from within the row HTML. I'm getting stuck on the function parameter, as I'm either messing up the escape character order or messing up the translation. I've already spent a few hours on this and tried doing research on Stack Overflow, so I'm hoping a second set of eyes would be able to help.
Here are the relevant pieces of code. The stored html is appended to my table row, which already works.
var strVar = 'myString';
var rowCount = $("#tbodyID td").closest("tr").length;
var rowNum = rowCount + 1;
var line17 = "<td><input type='number' class='form-control' name='named_qty' onblur='function(" + strVar + ")' id='row_R" + rowNum.toString() + "' /></td> ";
There are approximately 25 lines with varying html to be inserted. I was able to get it to work previously, but realized that a value was hardcoded and I needed it to be dynamic. The function it calls is accepting a string.
When inserted into the HTML document, this line should generally read:
<td><input type="number" class="form-control" name="named_qty" onblur="function('myString')" id="row_R2" /></td>
I did some more research and realized that I was using the JQuery blur() method as :
$('#id').blur( function() { }); and trying to call those functions, not realizing that the method only works for HTML elements that had been written to the DOM on page load.
Apparently the solution is to use the JQuery on() method as follows:
$(document).on("blur", '#id', function() { <insert code> });
From W3Schools,
Note: Event handlers attached using the on() method will work for both current and FUTURE elements (like a new element created by a script).
This removes the necessity to include the event function call in the HTML line to be appended to the DOM.
I have a form and I want to add new elements as you can see in this fiddle I used append $('#cvfields').append(campos); to add this elements but the jquery validation plugin started to giving me problems. I found this in some answers related whith this question
$('#titulo_'+campo).rules('add', {'required': true});
$('#tipo_'+campo).rules('add', {'required': true});
But when I added .rules code I received this error
Uncaught TypeError: Cannot read property 'form' of undefined
$.extend.rules
(anonymous function)
x.event.dispatch
v.handle
Hope you can help!
You have some issues with your code:
1) When you use the .rules('add') method on a selector of multiple elements, you must nest it inside a jQuery .each() or it won't be applied to all the matching elements.
$('.newinput').each(function() {
$(this).rules('add', {
'required': true
});
});
However, you can probably skip .rules() entirely. See item #2 below.
2) You can totally forget about item #1 above since you're only trying to make these new fields required. Simply add a required="required" attribute (which I see you've already done) when you create them and you will not need to worry about the .rules('add') method at all. Alternatively, you could use class="required" instead, which is the method I chose for the demo below.
3) This is why nothing was working: Your newly added elements must also contain unique names. It's a requirement of the plugin that all form inputs need a name atribute. It's how the plugin keeps track of the elements, so they all need to be unique. However, as per your code, they do not. Your newly created elements all have the same exact name assigned to them as your existing elements. Fix it by adding a counter and incrementing it to the name each time you append to the form.
$(function () {
validar();
cvFields();
});
function validar() {
$(".validate").validate({
....
});
}
function cvFields() {
var count = 0;
$('#addcvfields').click(function (e) {
e.preventDefault();
count++;
var total = $()
var campos = '' +
....
'<input name="profesorcv_titulo[' + count + ']" type="text" class="form-control required" placeholder="Titulo de Estudio o Experiencia">' +
....
'<select name="profesorcv_tipo[' + count + ']" class="form-control required">' +
....
'<textarea rows="3" name="profesorcv_descripcion[' + count + ']" class="form-control" id="profesorcv_descripcion" placeholder="Describe Brevemente"></textarea>' +
....;
$('#cvfields').append(campos);
});
}
you get these problems because the added form elements where not in the DOM when your form validation plugin get initialized. you have to call your validation plugin again, after you've added new elements to the DOM.
EDIT: I just had a look at your fiddle code. your problem can be solved by first calling cvFields() and then validar();
$(function(){
cvFields();
validar();
});
If you first call validar(), the function will look in the DOM (document) if there are elements with the class ".validate". If there are elements with this class they'll get processed by the function. However all the elements that are added to the DOM after the validar() function won't get processed because they were not present in the DOM when the validar() function was called.
If you want to get the validating work after you added more items to validate you simply have to do validar(); again.
I am using chosen plugin for a multiple select and I want to dynamically display all the selected options somewhere in the page.
I am able to show them, however, I also want to remove them if someone deselects/removes them. This is what I am struggling with.
My code till now looks like
$(".chosen-select").chosen({max_selected_options: 5}).change(function() {
var bStr = "#home-summary-right";
var htmlContent = $("#home-summary-right").html();
$(".search-choice").find("span").each(function() {
$(bStr).html("" + htmlContent);
toAppend = '<span>' + $(this).text() + '</span>';
$(bStr).append(toAppend);
});
});
Okay
Otherwise, is there any way to disable removing of elements once they are select in the multiple select? There is that cross, to which I can do display none, but I still don't know how can i disable the backspace from removing the elements.
Okay, I fixed it.
I used setTimeout in combination with bunch of other things.
The problem was after change, the inner html would return the same content as before... So I called an event after pretty much everything was done. Works super smooth!
I'm building a string of HTML based on JSON data. In the HTML is a <select> with its <option>s. If the <option>'s value is the same as some JSON data, it includes the selected="selected" attribute to the option tag as well. After that, the whole shebang is .append()ed to a display.
All of that seems to work fine and dandy, except that the selected option isn't selected. Checking the code in Chrome's Web Dev tools shows that the selected="selected" attribute is there. Doing a console.log() of the :selected options picks them up. However, when I drill down to a specific <option> and look at it, is shows the selected attribute as set to false.
Wha...?
I've tried using the .select() and .attr("selected","selected") jQuery methods after-the-fact to force the issue, but neither has made any difference.
Can anyone else figure out what's going on here? It might just be my squirrely ignorance, but this seems to me like it should be working.
Code for reference. dataArray is an array of objects. $display is the jQuery wrapped <table> the HTML is .append()ing to:
$orderNumberField = jQuery("#orderNumber");
_orderNumberArray = $.parseJSON( $orderNumberField.val() );
for( n in dataArray ) {
var _displayString = "";
// ... other table data cells ...
_displayString += "<td><select class='orderNumSelect'>";
_displayString += " <option value=''></option>";
for( i in _orderNumberArray ){
_displayString += "<option value='" + _orderNumberArray[i] + "'";
if( dataArray[n].orderNum == _orderNumberArray[i] ) _displayString += " selected='selected'";
_displayString += ">" + _orderNumberArray[i] + "</option>";
}
_displayString += "</select></td>";
// ... still other table data cells ...
$display.append( _displayString );
}
I'm not sure what's not working on your code,but you can try to generate the elements rather than appending text. I tested out with this code and it works fine
<script>
var dataArray=["test","testm2","Tasat3"];
function append(){
var td=document.createElement("td");
var sel=document.createElement("select");
var o=document.createElement("option");
sel.appendChild(o);
for (n in dataArray){
o=document.createElement("option");
o.value=dataArray[n];
o.text=dataArray[n];
if (n==1) o.selected=true;
sel.appendChild(o);
}
td.appendChild(sel);
document.getElementById("display").appendChild(td);
}
append();
</script>
As it turns out, the code outlined above was not at fault for the behavior I described. There is other code executing after it that resets form inputs. The jQuery selector in the other code was written too generally and was picking up the generated select fields also when it shouldn't have.
Thank you to all the commentors. I did end up rewriting the code to use DOM elements instead of generating a string, which is a little easier to read. Hooray for unintentional side effects.
Via ajax i retrieve some json data, make it as html and append it to my page.
Here I have a problem. I cant access element by id, if id is variable.
For example, http://jsfiddle.net/f8g5e/1/
<div id="123">Hello</div>
<div id="321">Bye</div>
<div id="out"></div>
$(function(){
key = '123';
$('#' + key).hide();
$('#321').hide();
});
The simples thing is works! #123 and #321 elements are hidden. Yeah, it's pretty obviosly.
But, in my project, when I append data to page:
$('#123') //returns element
$('#' + key) //returns null
Some code:
// generating data
var htmlData = '<div id="123">Greetings!</div><div id="321">Bye bye</div>';
// appending data
$('#tweets').empty();
$('#tweets').append(htmlData);
What are the possible causes i can't access elements?
Thanks.
UPDATE
Dont know how it works in JSFiddle, but when I changed my IDs to properly names it began to work now. Thanks to all! Next time, I'll take more attention to w3c dom standarts ;) Happy New Year!
The only reason I can think of that $('#'+key) wouldn't work is because the variable key is undefined.
Note: you're not supposed to start an ID with a number according to the W3C spec. However, most browsers allow it, so I doubt this is causing your problem.
However, if you have two divs with the same ID attribute, then JavaScript will only select the first one it finds -- IDs are supposed to be unique. If this is happening, use classes instead.
You can either do this:
$(function() {
$('#321,#123').hide();
});
or you can do this:
$(function() {
var key = '123';
var doit = '321';
$('#' + key + ',#' + doit).hide();
});