jQuery Find and Replace Element in string - javascript

There is HTML as a string returned by Ajax call.
headings
....
<div class="wrapper">
<input type="text" name="email" value="" />
</div>
....
I'm retrieving the .wrapper and input element
var elements = $(MY_HTML_STRING);
var domName = $('input[name="name"]', elements);
then making updates with both of them, and, my question is how to put them back into MY_HTML_STRING for further sending with ajax to different recipient.
Please let me know if it will be better to do with regex.
UPDATE:
Updates are: input value updating + .wrapper class updates and writing a piece of data into global variable. Everything can be done with regex, but I like the jQuery smoothness of code. The question is technically: if it's possible in the way I suggested.

After you've made your updates you can simply do something like the following (assuming there is only one div.wrapper that you're working with and that it is unique):
MY_HTML_STRING.replace(/<div class="wrapper">.*?<\/div>/, $('.wrapper').html());
Then you can make another AJAX call and pass the string back to the server.

Related

How to take result text when text-overflow property is applied

I have a div with css property text-overflow : ellipsis to add ellipsis and show the text in a single line.
When I perform jquery .text() or .html(), I get the full string, but I need the exact text displaying in the div currently (not the full string).
Can some one guide me how to take the exact displaying string using jquery or JS?
Actual String = "abcdefghijklmnop"
Due to CSS, the div displays "abcd..."
My expected result (using jQuery or JS) "abcd..."
This is not possible without trying to mimic CSS and recreate the strings with the ellipsis using JS.
The reason for this is that CSS only manipulates what is displayed to the user, not the HTML source itself. You can verify this by checking the source code for your document. This means that when you use .text() or .html() you get the values from the DOM, rather than what is displayed via the CSS filter.
There are a couple of hacks that does a pretty good job, but it is still no guarantee that the JS correctly mimics how CSS renders the text.
If you know the number of values you need every time then you can just use JS Like for example if it was always 4 values that gets entered in than it would be like this,
JS Fiddle
form
<form action="" method="post">
<p>
<label for="txt">My txt: </albel>
<input type="text" id="myTxt"><br />
<input type="submit" id="submitButton" value="Send">
</P>
</form>
js
document.getElementById('submitButton').onclick = function() {
myVariable = document.getElementById("myTxt").value;
alert(myVariable.slice(0, 4));
};
No matter what is typed in to the textbox it will be sliced to the first 4 characters.

Handling multi-line HTML inside Javascript

I am using Javascript to define a button behaviour on a web page. The behaviour I am after is to insert some new HTML somewhere on my page, but I would like to use the MVC extension method Html.EditorFor to define the new HTML which will be inserted.
What I would like to do is the following:
$("#myButton").click(function() {
$("#(Html.EditorFor(x => x.SomeModelProperty))").insertBefore(<somewhere>);
});
The problem I'm encountering is that the MvcHtmlString returned by the call to EditorFor renders as multi-line HTML, resulting in invalid Javascript:
$("<div>
<label for="ModelData_SomeModelProperty">SomeModelProperty</label>
</div>
<div> ....
In an ideal world, I could get EditorFor to somehow render all of the above on a single line, or use some kind of special Javascript syntax to define a multi-line string (like using single quotes in C#), but so far I'm drawing a blank.
I've tried calling ToHtmlString and hand-editing the resulting string to remove line-breaks, and I'm aware that I can escape the new lines in Javascript using a /, but the problem with doing so is that I then have to handle the escaped HTML, which looks a little like the following:
$("<div>
<label for="ModelData_SomeModelProperty">SomeModelProperty</label>
</div>
<div> .... (you get the idea)
I was just wondering whether anyone had tried anything similar and might have a more elegant approach?
One way would be to get it written into a hidden div in html instead of directly into the javascript. Then you can just read it from the dom to use in you script.
So you page would have a
<div style="display:none" id="hiddenArea">
...insert whatever you want in here
with newline or whatever...
</div>
And then in your javascript:
$("#myButton").click(function() {
var source = $("#hiddenArea").html();
$(source).insertBefore(<somewhere>);
});
You could maybe create a HTML helper so you much more control on what's returned and how it is formatted.
http://www.codeproject.com/Tips/720515/Custom-HTML-Helper-for-MVC-Application

What is the typical technique of loading dynamic elements from the server and/or client?

Let's say I have a simple form setup. I can dynamically add the below element as mant times to a form via javascript.
<div class="aComplicateDiv">
<input type="text" name="myValue">
</div>
Now let's say we save these values, and then want to edit them. I can query the DB on the edit page and then from the server side, display the div with the input fields.
My issue is, when I'm adding this div, im using javascript to build the elements. However, when I display these elements on the server side, I'm using php. Seems to be repetitive, especially if I want to change the elements. I can however, from the server side, call javascript functions that pass in values to build it via javascript on the edit page, but that seems to not be the correct process. Any insight would be great on if there is a better approach or not.
The approach I mainly use in that kind situations (especially when the repeating part gets more complicated):
In PHP (extremly simplified):
function addRow($index, $data) {
echo '<div class="aComplicateDiv" id="row-'.$index.'">
<input type="text" name="myValue['.$index.']" value="'.htmlspecialchars($data).'">
</div>';
}
foreach($dataFromDb as $row) {
addRow($row['id'], $row['value']);
}
addRow('TEMPLATE', '');
In Javascript (demo)
var nextIndex = 2; // Find a way to calculate this
$('#add').click(function() {
// Append a clone of the template to a temporary div
// From that div we can get the html-content
var html = $('<div>').append(
$('#row-TEMPLATE').clone()
).html().replace(/TEMPLATE/g, nextIndex++);
$('#row-TEMPLATE').before(html);
});

Proper way to retrive HTML textbox data using JavaScript

Assuming I have a simple HTML page like the following:
<html>
<head>...</head>
<body>
<input type="text" id="mytextarea" />
<input type="button" id="button1" onClick="..." />
<input type="button" id="button2" onClick="..." />
</body>
</html>
What is the best way to access the text in the text-field with id="mytextarea" in a JavaScript function, without creating code heavily coupled to the HTML page, given the knowledge that button1 and button2 cause different manipulations on the text?
Just as an example, assume I am expecting a binary number in the text field, and button1 will convert it to an integer decimal number, but button two will convert it to a fractional decimal number. How can I handle this without tightly coupling the JavaScript code to the HTML page? Is there some way to send the data in mytextarea down to the JavaScript code, without having to use a document.getElementById('mytextarea') in the JavaScript functions themselves?
Perhaps I should clarify,
I am not looking for an alternative to using getElementById, I am looking for a way to write JavaScript code that can use a text-field in an HTML page without being coupled to it. In other words, I would like to know how to write JavaScript functions and HTML pages in such a way that (1) the JavaScript functions can perform work on data in the HTML page and (2) the JavaScript function can be be moved to another HTML page and used there, without changing said function.
I think this is what you want:
First you create an object called Textarea that lets you pass a textarea element as an argument:
function Textarea(textarea) {
this.container = textarea;
this.value = textarea.value
};
Then you can add methods shared by every instance of the Textarea object:
Textarea.prototype.ChangeValue = function(){
console.log( 'Please add your ' + this.value );
};
In this way, you can pass mytextarea and modify it as you want. This allows to reuse properties and methods in your object in other textareas or other projects where you need it.
t = new Textarea(document.getElementById('mytextarea'));
t.ChangeValue();
Demo: http://jsfiddle.net/SQ2EC/
Since you need some way to inform the functions about the elements to be operated on, there are two simple options. You can pass a reference to an element as a parameter when calling a function, as in
onclick="manipulate(document.getElementById('mytextarea'))"
Or you could pass just the id attribute value:
onclick="manipulate('mytextarea')"
in which case the function would need to use document.getElementById(), but on its parameter, not a wired-in string.
The first approach is more flexible in the sense that it lets you construct a reference in some other way too, e.g. document.getElementsByTagName('textarea')[0].
You could combine the approaches, by writing the function so that it can handle both kinds of parameters. It could e.g. first check whether its argument is of string type and use document.getElementById() on it if it is, otherwise expect it to be a reference to an element. And you should probably have some sanity checks in the function, testing that what you get or construct is really a reference to a textarea element.
I dint get what exactly you want to do but here you can get value of textbox on it's change event
<script>
$(document).ready(function () {
$('input[id$=mytextarea]').change(function () {
alert($(this).val());
.............
now you have got the value so convert it to decimal and do other stuff
});
});
</script>

javascript not getting value of input box

I seem to be having trouble with passing the value of an input box to anything else in my javascript.
It's not producing any errors - and I remember reading somewhere that you can have issues if the document hasn't finished loading - but I'm pretty sure it has!
The code in question is as follows in the javascript:
var address = getElementById(addyInput).value;
document.getElementById('add').innerHTML = address;
And in the HTML
<form>
<input name="addyInput" placeholder="Don't forget postcode!">
</form>
<button id="start" onclick="initialize()">Start!</button>
<p>Address Test
<div id="add"></div>
</p>
I know that the button itself is working as it fires the rest of my code fine without the offending code - however the moment I uncomment that little block at the top, it just does nothing. (no errors etc)
Any help on that one would be hot! Thanks :)
Update:
I now have it working! Thanks muchly for all the help!!
Your form needs to look like this (add an id attribute):
<form>
<input id="addyInput" name="addyInput" placeholder="Don't forget postcode!">
</form>
And the first line of Javascript needs to look like this (since getElementById is expecting an ID rather than a name).
var address = getElementById('addyInput').value;
Additionally, getElementById expects the id argument to be a string (hence the quotes). If you pass it addyInput without quotes, it'll try to interpret addyInput as a variable which has a value of undefined and you won't get back the DOM element you want.
Or, if you were using jQuery, you could leave the form markup as-is and change the Javascript to this:
var address = $('input[name=addyInput]').val();
Make sure to specify and id on the input. You only have a name.
You need to add the id "addyInput" to your form input rather than just the name.
getElementById expects a string.
var address = getElementById('addyInput').value;
If you put this directly into a script section in the head, then you will have a problem because the page is not loaded completely but the code is executed already.
And of course you should define an id for the input element as the others already said.
what you are getting is an array, you need to fetch your array into some readable data. Try something like:
$value = array_shift( $yourarray );
or if it's a multi value array you can just loop it to fetch out the values.

Categories