Using jQuery replaceWith on html elements - javascript

I'm writing an MVC application and on one page I need to dynamically give an ID to all the elements because of the way the table is rendered and how data is passed to an from it. When I run this, all the elements are replaced with , however it is removing the content in between the tags. Is there any way to make it only replace the starting tag and not touch the rest, or another jQuery function to do this? My code is below:
<script type="text/javascript" charset="utf-8">
$(document).ready(function () {
var oTable1 = $('#example1').dataTable({
sScrollX: "100%",
sScrollY: "200px",
bFilter: false,
bScrollCollapse: true,
bPaginate: false,
bScrollInfinite: true,
iScollLoadGap: 10,
oLanguage: {
sZeroRecords: "There are no records that match your search criterion",
}
}).makeEditable({ sUpdateURL: "/Home/UpdateData" });
});
</script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function () { var editChange = $('td').replaceWith('<td id = "#Html.ValueFor(x => x.name)" >'); });
</script>
Any help is appreciated.

Instead of using replaceWith may I suggest the use of another function, the function .attr() that is meant to replaced the attributes of an element.
$('td').attr('id','#Html.ValueFor(x => x.name)');
Also, be careful because the ASP values will not be available once in the client side. Your selector $('td') is pretty general, and IDS must be unique.

Try explicitly setting the id on the TD element(s)
$('td').each(function() {
this.id = #Html.ValueFor(x => x.name);
});

Related

How do I count the number of elements in a sortable div?

I have multiple divs in an HTML document with smaller divs within them that can be sorted among each other. When the document is loaded, a random amount of those smaller divs are appended to #boxtop.
Here's my HTML:
<html>
<body>
<head>
<title></title>
<script link src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="jquery-ui.min.css">
<link rel = "stylesheet" type" type="text/css" href = "style.css">
<script src="jquery-ui.min.js"></script>
<div id = "boxtop" class = "dragInto"></div>
<button type="button" id="button">My Children!!!</button>
<div id = "eqbox"></div>
<div id = "box1" class = "ansBox"></div>
<div id = "box2" class = "ansBox"></div>
<div id = "box3" class = "ansBox"></div>
</head>
</body>
</html>
Here's my relevent jQuery
$(document).ready(function()
{
$("#boxtop").sortable
({
connectWith: ".ansBox"
});
$(".ansBox").sortable
({
connectWith: ".ansBox"
});
});
$(document).ready(function()
{
$("dragInto").droppable
({
accept: ".box"
});
});
var numChild = $("#boxtop").length;
$(document).ready(function()
{
$("#button").click(function()
{
console.log(numChild);
});
});
My question is: How can I get the number of elements in a sorted div. I currently try and print that value to the console using numChild but that prints "1". And if I were to drag a bunch of elements from #boxtop to .box1, how could I get the number of elements inside .box1?
The .length property tells you how many elements belong to the jQuery object you call it on. So given that $("#boxtop") matches one element, $("#boxtop").length will be 1.
To find out how many elements are inside #boxtop you have to select all of its descendants and then check the .length:
// All descendants:
$("#boxtop").find("*").length // or:
$("#boxtop *").length
// Or count immediate children only:
$("#boxtop").children().length
In your case I think checking immediate children is probably what you want. But don't set a global variable like:
var numChild = $("#boxtop").children().length;
...because that will set numChild to the length when the page first opens, before the user has started interacting with it. You need to check $("#boxtop").children().length or $(".box1").children().length at the point where the value is needed.
As an aside, you don't need three separate $(document).ready(...) handlers: combine all of your code into a single ready handler, or if you put your <script> element at the end of the body you don't need a ready handler at all.
You need to catch update or stop event from sortable instance. Detailed document just right there
https://api.jqueryui.com/sortable/#event-stop
https://api.jqueryui.com/sortable/#event-update
Live Demo And Working Code

jQuery .prepend() Not Working

and I am trying to prepend an option value from a select. I need the output to start with a capital "K". Here is my jQuery:
$(document).ready(function () {
$(".dialogbox").dialog({
modal: true,
autoOpen: false
});
$(".dropdown").change(function () {
$(".dialogbox").dialog("open");
$(".dialogbox").change("puff");
});
$('select.dropdown').change(function () {
var capacityValue = $('select.dropdown').find(':selected').data('capacity').toUpperCase();
$('.dialogbox').val(capacityValue);
});
});
and here is my fiddle
I've tried
$('.dialogbox').val(capacityValue).prepend( 'K' );
but that didn't seem to work. All the examples I've seen indicate that this should work. Thanks in advance for the help.
There are quite a few problems with your code:
(1) .prepend() is for prepending an element as a child of another element. You are trying to call it on a string. I think you want to use string concatenation:
"K" + $('select.dropdown').find(':selected').data('capacity')
(2) You are missing an = in your html for the dropdown's "name" attribute:
<select class='dropdown' name='dropdown'>
(3) You have two elements with class="dialogbox", so the following opens two dialogs:
$(".dialogbox").dialog("open");
You could either use two different class names, or include the element types in the selectors to distinguish between them: 'div.dialogbox' & 'input.dialogbox'
(4) You are attaching two change event handlers to the dropdown. There's no guarantee on the order they are called. You should combine them into one.
(5) You should use .text() or .html() to insert text into an element, not .val(). Use .val() just for setting the value of an input element.
(6) You can establish the animation effect for the opening of a dialog by including the show option:
show: 'puff'
Or:
show: { effect: 'puff', duration: 1000 }
Try the following:
$(".dropdown").change(function () {
var capacityValue = "K" + $(this).find(':selected').data('capacity').toUpperCase();
$('div.dialogbox').text(capacityValue).dialog("open");
$('input.dialogbox').val(capacityValue);
});
jsfiddle
I saw your fiddle I think you don't undestand what prepend does. capacityValue it's just value of attribute.
.prepend
Description: Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.
http://api.jquery.com/prepend/
capacityValue it is not element, it's object string, not more.
.prepend() is to prepend a dom element. In your case just Try to prepend the text like this,
var capacityValue = "K"+ $('select.dropdown').find(':selected').data('capacity');
Updated fiddle
Reduced code to one line and corrected it ! **
$('select.dropdown').change(function () {
$('.dialogbox').val("k"+$(this).val());
});
you can easily achieve it without prepend method
solution is here
I've updated your fiddle, check here.
HTML:
<select class='dropdown' name 'dropdown'>
<option data-selected='opts1' data-capacity='opt1' value='opt1'>Option 1</option>
<option data-selected='opts2' data-capacity='opt2' value='opt2'>Option 2</option>
<option data-selected='opts3' data-capacity='opt3' value='opt3'>Option 3</option>
</select>
<div class='dialogbox' title='Dialogbox'></div>
<input type="text" class="dialogbox" readonly />-->
Javascript:
$(document).ready(function () {
$("div.dialogbox").dialog({
modal: true,
autoOpen: false
});
$("input.dialogbox").change(function () {
$("div.dialogbox").dialog("open");
});
$('select.dropdown').change(function () {
var capacityValue = "k".toUpperCase() + $(this).find(':selected').data('capacity');
$('div.dialogbox').text(capacityValue);
$('input.dialogbox').val(capacityValue);
$('input.dialogbox').change();
});
});

How to set position for dialog created via JavaScript

HTML:
Link
JavaScript
$(document).ready(function() {
$(document.body).on('click',"a",function(event){
if ($(this).hasClass('ui-dialog-titlebar-close')) return;
event.preventDefault();
var data = '<div id="dialog" title="Basic dialog">';
data += '<p>Hello.</p></div>';
$(data).dialog();
});
});
I want to set a position for this dialog. I've tried changing $(data).dialog(); to $(data).dialog('option', 'position', [200,300]);, but it doesn't work. How can I set it?
jsFiddle: http://jsfiddle.net/fcTcf/
it should be:
$(data).dialog({
position: [200, 300]
});
The syntax $(data).dialog('option', 'option-name', value) is used for changing an option of a dialog that has already been initialized. But if you want to specify options at initialization time, you do so using a option object as the argument to the widget.
There is a link to api documentation for the jQuery Dialog Widget and this jQuery position will help you if you want more granular control of the position.
You're using the selector incorrectly.
$(data) where $data is not a class or id, data is a string containing html.
Try $("#dialog").dialog(); And then you surely would be able to figure it out with the API-documentation.
$(document).ready(function() {
$(document.body).on('click',"a",function(event){
if ($(this).hasClass('ui-dialog-titlebar-close')) return;
event.preventDefault();
var data = '<div id="dialog" title="Basic dialog">';
data += '<p>Hello.</p></div>';
var options={
position:[200,300]
};
$(data).dialog(options);
});
});
You can set 'option' like this

Dynamically Replacing Content with Javascript and Links

http://jsfiddle.net/bUjx7/42/
<script type='text/javascript' src='http://code.jquery.com/jquery-1.9.1.js'>
</script>
<script type='text/javascript'>
$(document).ready(function () {
$('.fieldreplace a').click(function () {
$('#fieldmatch, .fieldgame').hide();
var region = $(this).data('region');
$('#' + region).show();
});
});
</script>
I'm trying to make it so clicking one link will replace content in all the cells, and not, as it is, in just one cell.
Help?
You can replace the contends of all tds like?
$('#tableId td').html('content to update on all cells');
There are several problems in your code.
I see you have specify id="fieldgame1" many times, remember id should be unique for every element.
You would make use of class selector instead of id selector for selecting all elements.
Now, you would make the cell content with different classes, and use class selector to hide/show them.
HTML
<div class="fieldmatch" >2-5</div>
<div class="fieldgame1" >1-6</div>
<div class="fieldgame2" >6-1</div>
<div class="fieldgame3" >2-5</div>
Css
.fieldgame1, .fieldgame2, .fieldgame3 {
display:none;
}
JavaScript
$(document).ready(function () {
$('.fieldreplace a').click(function () {
$('#fieldmatch, .fieldgame').hide();
var region = $(this).data('region');
$('#' + region).show();
});
});
Code example on : http://jsfiddle.net/bUjx7/44/

JQuery replace entire DIV using .load()

I want to refresh a <div> on the close of a jQuery UI Modal Dialog.
My code is:
var dialog = jQuery('#divPopup').dialog({
autoOpen: false,
height: 450,
width: 650,
modal: true,
open: function(event, ui) {
jQuery('body').css('overflow', 'hidden');
},
close: function(event, ui) {
jQuery('#divPopup').dialog('destroy').remove();
jQuery("#bodyId").load("http://www.xyz.com/ #bodyId");
}
});
But instead of replacing it, that adds the new <div> inside the old <div>:
<div id="bodyId">
<div id="bodyId">
New Response
</div>
</div>
I want to replace old div bodyId with new div bodyId.
Try to replace this:
jQuery("#bodyId").load("http://www.xyz.com/ #bodyId");
... with this:
jQuery("#bodyId").load("http://www.xyz.com/ #bodyId > *");
This works because you can use any selector after the URL. By using #bodyId > * instead of just #bodyId, you match everything that is inside the div, instead of the div itself.
You need this because .load() will not replace an element; it will append the result of the AJAX call to the element.
Alternatively, you could use .get() to load the data and manually perform the selection, like so:
$.get('http://www.xyz.com/', function(data) {
var newContent = $(data).find('#bodyId').children();
$('#bodyId').empty().append(newContent);
});
Examples of both methods are online here: http://jsfiddle.net/PPvG/47qz3/
You could also use jquery.get.
$.get('http://www.xyz.com/', function(data) {
$('#bodyId').html(data);
});
you may be use this code like
$('#bodyID').remove();
$('#bodyID').load();

Categories

Resources