Using Javascript .focus() highlights text - javascript

I have a form like so:
<form action='word.php' name = 'searchbox'>
<input type='text' name='word' id = 'searchbox' value = 'default'>
</form>
In my body I have:
<body onLoad="searchbox.word.focus()">
You can see the fiddle here:
http://jsfiddle.net/WEZ7S/
What I'm trying to achieve is just have a blinking cursor at the end of "default", but instead the whole word gets selected instead.
Surprisingly Google hasn't been able to find any solutions. How would I do this?

You can get around this by resetting the .value property of the element:
searchbox.word.focus();
searchbox.word.value = searchbox.word.value;
There are also less hacky solutions: Use JavaScript to place cursor at end of text in text input element
Demo: http://jsfiddle.net/WEZ7S/1/

From a previously answered question: https://stackoverflow.com/a/13371452/1238887
Here's a nifty little trick:
$(document).ready(function() {
var $field = $("#searchbox"),
oldVal = $field.val();
$field.focus().val('').val(oldVal);
});
DEMO: http://jsfiddle.net/X7Y8S/

Use setSelectionRange (Chrm, FF):
var len = searchbox.word.length;
searchbox.word.focus();
searchbox.word.setSelectionRange(len, len);

Related

Editing a text in javascript with the result of a dropdown value

I made a piece of code from what I could find on the internet to display in a field, the value selected from a dropdown list with this code.
<input type="text" id="text">
<script type="text/javascript">
function update() {
var select = document.getElementById('list-category');
var option = select.options[select.selectedIndex];
document.getElementById('text').value = option.text;
}
update();
</script>
This one works very well but the problem is that the text is displayed in an <input>. It's not very aesthetic and above all, you can have fun modifying it. Do you know how I could make the text display simply? Without necessarily putting it in an <input> ? I have try with console.writebut I don't know the args to pass. Thanks for the help.
Instead of using the <input> tag, you can use the <span> tag. You can update its value with innerHtml property.

get the html of element itself using jquery .html()

How to get the html of element itself using Jquery html. In the below code I would like get the input element inside div using JQuery as shwon below
<div id="content">content div</div>
<input type='text' id="scheduledDate" class="datetime" />
$(function() {
console.log($('#scheduledDate').html('dsadasdasd'));
$('#content').html($('#scheduledDate').html());
});
EDIT:
Can I get the $("#scheduledDate") as string which represent the real html code of the input box, because my final requirement is I want to pass it to some other SubView( I am using backboneJS) and eventually use that html code in a dust file.
My original requirement was to get that input field as string so that I can pass it to some other function. I know, if I keep it inside a DIV or some other container, I can get the html by using .html method of JQuery. I dont want use some other for that purpose. I am just trying to get html content of the input box itself using it's id.
If you want to move the input element into div, try this:
$('#content').append($('#scheduledDate'));
If you want to copy the input element into div, try this:
$('#content').append($('#scheduledDate').clone());
Note: after move or copy element, the event listener may need be registered again.
$(function() {
var content = $('#content');
var scheduledDate = $('#scheduledDate');
content.empty();
content.append(scheduledDate.clone());
});
As the original author has stated that they explicitly want the html of the input:
$(function() {
var scheduledDate = $('#scheduledDate').clone();
var temporaryElement = $('<div></div>');
var scheduleDateAsString = temporaryElement.append(scheduledDate).html();
// do what you want with the html such as log it
console.log(scheduleDateAsString);
// or store it back into #content
$('#content').empty().append(scheduleDateAsString);
});
Is how I would implement this. See below for a working example:
https://jsfiddle.net/wzy168xy/2/
A plain or pure JavaScript method, can do better...
scheduledDate.outerHTML //HTML5
or calling by
document.getElementById("scheduledDate").outerHTML //HTML4.01 -FF.
should do/return the same, e.g.:
>> '<input id="scheduledDate" type="text" value="" calss="datetime">'
if this, is what you are asking for
fiddle
p.s.: what do you mean by "calss" ? :-)
This can be done the following ways:
1.Input box moved to the div and the div content remains along with the added input
$(document).ready(function() {
var $inputBox = $("#scheduledDate");
$("#content").append($inputBox);
});
2.The div is replaced with the copy of the input box(as nnn pointed out)
$(document).ready(function() {
var $inputBox = $("#scheduledDate");
var $clonedInputBox = $("#scheduledDate").clone();
$("#content").html($clonedInputBox);
});
Div is replaced by the original input box
$(document).ready(function() {
var $inputBox = $("#scheduledDate");
$("#content").html($inputBox);
});
https://jsfiddle.net/atg5m6ym/4485/
EDIT 1:
to get the input html as string inside the div itself use this
$("#scheduledDate").prop('outerHTML')
This will give the input objects html as string
Check this js fiddle and tell if this is what you need
https://jsfiddle.net/atg5m6ym/4496/

Remove a character from the middle of a string: without removing inner element

This one has me stumped. I want to remove the "+" from a label element. Here's the HTML:
<label class="option" for="edit-attributes-21-33">
<input type="radio" id="edit-attributes-21-33" name="attributes[21]"
value="33" checked="checked" class="form-radio"> 4 oz, +$15.00</label>
I started with this
$(".option").each(function(index, value) {
$(this).text( $(this).text().replace("+", ""));
})
This removes the "+" but also strips out the input element. So then I tried:
$(".option").each(function(index, value) {
var oldString = $(this).html();
var newString = oldString.replace("+", "");
console.log(oldString, newString);
$(this).text(newString);
})
This makes a string of the correct html mark-up, but it's a string and is passed back to the DOM that way. I've seen another post with the same problem, but no solution.
You can achieve what you want using your code by using .html() instead of .text():
$(".option").each(function(index, value) {
var oldString = $(this).html();
var newString = oldString.replace("+", "");
console.log(oldString, newString);
$(this).html(newString);
});
Here's the JQuery .html() method ref: https://api.jquery.com/html/
Here's the Fiddle: https://jsfiddle.net/Darkseal/1c572Luw/
I also slightly modified your <input> end tag to make it XHTML compliant.
What you're looking for is called a textNode. I gave your label an ID to make it easier, but the priciple remains the same for other selectors:
var node = document.getElementById("example").childNodes[2];
node.nodeValue = node.nodeValue.replace("+", "");
With a simple demo.
You should try to use plain JS as much as you can in favour in jQuery. Plain JS is often a lot faster than jQuery is.
After the comment, if you don't know the exact position of the textnode, check this.
Late answer, just for the sake of showing a different approach using jQuery.
Here you would keep the input state, and wouldn't have the risk of replacing chars that you don't want to. Let's say you used + somewhere else, not just on the label text.
$(function () {
$('label.option').each(function () {
var label = $(this);
var input = $('input.form-radio', this);
var text = label.text();
// Clean up the label contents.
label.empty();
// Replace the char occurrences.
text = text.replace(/\+/g, "");
// Append both the input and the modified text.
label.append(input).append(text);
});
});
Demo

How to append text to '<textarea>'?

I have <textarea> where user can type in his message to the world! Below, there are upload buttons... I would love to add link to uploaded file (don't worry, I have it); right next to the text that he was typing in.
Like, he types in 'Hello, world!', then uploads the file (its done via AJAX), and the link to that file is added in next line to the content of <textarea>. Attention! Is it possible to keep cursor (place where he left to type) in the same place?
All that may be done with jQuery... Any ideas? I know that there are method 'append()', but it won't be for this situation, right?
Try
var myTextArea = $('#myTextarea');
myTextArea.val(myTextArea.val() + '\nYour appended stuff');
This took me a while, but the following jQuery will do exactly what you want -- it not only appends text, but also keeps the cursor in the exact same spot by storing it and then resetting it:
var selectionStart = $('#your_textarea')[0].selectionStart;
var selectionEnd = $('#your_textarea')[0].selectionEnd;
$('#your_textarea').val($('#your_textarea').val() + 'The text you want to append');
$('#your_textarea')[0].selectionStart = selectionStart;
$('#your_textarea')[0].selectionEnd = selectionEnd;
You should probably wrap this in a function though.
You may take a look at the following answer which presents a nice plugin for inserting text at the caret position in a <textarea>.
You can use any of the available caret plugins for jQuery and basically:
Store the current caret position
Append the text to the textarea
Use the plugin to replace the caret position
If you want an "append" function in jQuery, one is easy enough to make:
(function($){
$.fn.extend({
valAppend: function(text){
return this.each(function(i,e){
var $e = $(e);
$e.val($e.val() + text);
});
}
});
})(jQuery);
Then you can use it by making a call to .valAppend(), referencing the input field(s).
You could use my Rangy inputs jQuery plugin for this, which works in all major browsers.
var $textarea = $("your_textarea_id");
var sel = $textarea.getSelection();
$textarea.insertText("\nSome text", sel.end).setSelection(sel.start, sel.end);

select created element

$(iframe).bind('keypress', function (e) {
if (e.which == 13) {
var range = iframe.getSelection().getRangeAt(0);
var nodeText = $(range.startContainer, iframe).parent().html();
var leftPart = nodeText.substr(0, range.endOffset);
var rightPart = nodeText.substr(range.endOffset);
$(range.startContainer, iframe).parent().replaceWith('<big>' + leftPart + '</big><p>' + rightPart + '</p>');
return false;
}
});
I've got iframe with some content, e.g:
<p>someText</p>
When i place cursor between "some" and "text", and press enter, i want it to be splitted into this:
<big>some</big><p>Text</p>
everything seems to be working ok, but I also need to change cursor position to the beginnings of this: <p>Text</p>
I know how to set cursor position, but I need to select that element. just $('p', iframe) won't work, because I can have multiply <p> items in iframe. any ideas?
This is an unholy mix of DOM, which considers everything in terms of nodes and offsets, and jQuery-ish HTML-as-strings. The two do not mix well. You've misunderstood the endOffset and startOffset properties of DOM Ranges: they're not offsets within the innerHTML of the container. I suggest looking at MDC or the spec and refactoring your code to only use DOM nodes and not strings of HTML.
Denis ,
Give a common class name to all of them , so that it will effect on the elements.
I would add a dynamic id attribute (or use the metadata plugin) using jQuery to identify the split paragraph. And based on the identified split string place the cursor before the <p> tag. Do make sure to remove the id attribute (or some metadata) once you are done placing the cursor, so that any other splits or a backspace on the same <p> doesn't result in unintended consequences
Hope that helps
I found a nice solution without adding id or class to element. i changed this:
$(range.startContainer, iframe).parent().replaceWith('<big>'+leftPart+'</big><p>'+rightPart+'</p>');
to this:
var leftObject = $('<big>'+leftPart+'</big>');
var rightObject = $('<p>'+rightPart+'</p>');
$(range.startContainer, iframe).parent().replaceWith(leftObject);
leftObject.after(rightObject);
now i got both elements selected in leftObject and rightObject

Categories

Resources