How can I prevent removing the selection from text after a click? - javascript

I'm working on an admin-panel where the inputs are contenteditable divs. I also have a toolbar (containing some formatting buttons), that shows up if you have any selected text inside the div, and will be removed if not.
The problem is, that when I click to any button in the toolbar, the selection from the document will be removed, so I can't insert for example a tag before and after the text.
Can I prevent this behaviour, or is there any workaround for this?

It's not inevitable that the selection is lost when the user clicks a button. The two ways I know to avoid it are:
Use the mousedown rather than the click event on the button and prevent the event's default action
Make the button unselectable.
See https://stackoverflow.com/a/11787147/96100.

I typically handle such cases by tracing the cursor change position within the editable control. Set up a variable to hold the last position, update it with each position change, then read the variable from your toolbar's event.
I don't work with JS enough to know the specific syntax for this offhand, but it's pretty general stuff for the most part.

I fixed it with saving the range variable into a window variable (global), after mouseup. Then use this to find and replace the elements. And it works!
I use this function to define whether a string is selected or not:
function isTextSelected(input) {
var sel,range,selectedText;
if(window.getSelection) {
sel = window.getSelection();
if(sel.rangeCount) {
range = sel.getRangeAt(0);
selectedText = range.toString();
if(selectedText.length) {
window._selection = range; // <-- This line saved my life! :)
return true;
}
}
}
}
And this is the code of the "B" button:
$('.editor-icon.b').click(function(e){
var element = document.createElement('b');
var selectedText = document.createTextNode(window._selection.toString());
element.appendChild(selectedText);
window._selection.deleteContents();
window._selection.insertNode(element);
window._selection = false;
});

Related

Click all checkboxes on a webpage with HTML script (quickbooks/Safar)

So I created the following script to select all check boxes on a page
(function(d) {
var input = d.querySelectorAll('input[type="checkbox"]');
var i = input.length;
while (i--) {
input[i].checked = true;
}
})(this.document);
It does work to do that, however when trying it in Quickbooks while it does select all the boxes, the website does not register it as actually being selected (the total cost at the bottom remains the same, its like it superficially checks the boxes, visually only with no actual register). Any help would be great.
EDIT: Maybe simulating a click instead of changing the box values?
The only thing that changes when physically selecting a box is the value posted below changes to true from false
You should do :
input[i].setAttribute("checked", "");
The checked attribute is a boolean attribute, so the standard way to add it to an element is to pass an empty string for value.
https://developer.mozilla.org/fr/docs/Web/API/Element/setAttribute#Exemple

Not editable,removable part of a textarea

I have a simple textarea and It has a default value. I want to hold this value everytime. User should not remove this value but he can add extra string.
<textarea>This is contstant</textarea>
As you see above. It has a default value. How can I protect this value? But user can add something after default value like below.
<textarea>This is contstant and extra things by user</textarea>
So how can do a partially editable textarea with default value?
You can attach an event handler to the <textarea> that does a simple validation every time it changes. If it tries to change to where your constant is partially destroyed, overwrite the X characters of the string value.
$('#foo').keydown(function () {
if ($(this).val().indexOf("This is constant. ") !== 0) {
var length = "This is constant. ".length;
var current = $(this).val();
var after = current.slice(length);
$(this).val("This is constant. " + after);
}
});
Here is a example on JSFiddle.
I recommend using JQuery for this because <textarea> doesn't actually have a value, or I think even a text attribute that you can check. JQuery just abstracts away <textarea>'s quirks.
I would go this way:
Style the textarea to remove the border.
Put a div on top which contains the constant text.
Wrap both elements in a div to give it a common border.
That way, the constant text will appear as if it was part of the textarea but it's not.
When you submit the form, prepend the static text to the field value.

Prevent jiggling when auto-adjusting width of text input

I managed to write an angular directive (I have extracted it to pure jQuery for this post) to auto-adjust the width of a text input.
However, it seems like the width of the input field is not changing fast enough because the contents scroll back and forth.
Type into the input field to see for yourself: Demo on JSFiddle
Here is the code:
var $element = $('#my-input');
// create dummy element to calculate text width in pixels
var dummy = $('<span></span>');
$('body').append(dummy);
dummy.css('visibility', 'hidden');
// apply all relevant text styling from our input element
dummy.css('fontFamily', $element.css('fontFamily'));
dummy.css('fontSize', $element.css('fontSize'));
dummy.css('fontWeight', $element.css('fontWeight'));
dummy.css('letterSpacing', $element.css('letterSpacing'));
var resize = function() {
dummy.html($element.val().replace(/ /g, ' '));
$element.width(dummy.innerWidth() + 1); // it's 1px off for some reason
};
resize();
$element.on('keyup', resize);
How can I prevent this from happening? I've already experimented some with scrolling the input field but to no success. Anybody have an idea?
The keyup that you use is triggered only when the user release its keyboard key, so only after that the character is added on the input field and its content is bigger than its width. It cause the jiggeling you talk about.
You should add the input event to your listener event list. This event, supported only by new browsers, is triggered everytime a character is changed in the input field.
You can check this answer about input field change events to learn more.

set value to jquery autocomplete combobox

I am using jquery autocomplete combobox
and everything is ok. But I also want to set specific value through JavaScript like $("#value").val("somevalue") and it set to select element, but no changes in input element with autocomplete.
Of course, I can select this input and set value directly, but is it some other ways to do that? I try set bind to this.element like this.element.bind("change", function(){alert(1)}) but it was no effects. And I don't know why.
Edit
I found a workaround for this case. But I don't like it. I have added the following code to _create function for ui.combobox
this.element.bind("change", function() {
input.val( $(select).find("option:selected").text());
});
And when I need to change the value I can use $("#selector").val("specificvalue").trigger("change");
Is this demo what you are looking for?
The link sets the value of the jQuery UI autocomplete to Java. The focus is left on the input so that the normal keyboard events can be used to navigate the options.
Edit: How about adding another function to the combobox like this:
autocomplete : function(value) {
this.element.val(value);
this.input.val(value);
}
and calling it with the value you want to set:
$('#combobox').combobox('autocomplete', 'Java');
Updated demo
I cannot find any available existing function to do what you want, but this seems to work nicely for me. Hope it is closer to the behaviour you require.
I managed a quick and dirty way of setting the value. But, you do need to know both the value and the text of the item that you want to display on the dropdown.
var myValue = foo; // value that you want selected
var myText = bar; // text that you want to display
// You first need to set the value of the (hidden) select list
$('#myCombo').val(myValue);
// ...then you need to set the display text of the actual autocomplete box.
$('#myCombo').siblings('.ui-combobox').find('.ui-autocomplete-input').val(myText);
#andyb,
i think rewrite:
autocomplete: function (value) {
this.element.val(value);
var selected = this.element.children(":selected"),
value = selected.val() ? selected.text() : "";
this.input.val(value);
}
I really like what andyb did, but I needed it to do a little more around event handling to be able to handle triggering the a change event because "selected" doesn't handle when hitting enter or losing focus on the input (hitting tab or mouse click).
As such, using what andyb did as a base as well as the latest version of the jQuery Autocomplete script, I created the following solution: DEMO
Enter: Chooses the first item if menu is visible
Focus Lost: Partial match triggers not found message and clears entry (jQuery UI), but fully typed answer "selects" that value (not case sensative)
How Change method can be utlized:
$("#combobox").combobox({
selected: function (event, ui) {
$("#output").text("Selected Event >>> " + $("#combobox").val());
}
})
.change(function (e) {
$("#output").text("Change Event >>> " + $("#combobox").val());
});
Hopefully this helps others who need additional change event functionality to compensate for gaps that "selected" leaves open.
http://jsfiddle.net/nhJDd/
$(".document").ready(function(){
$("select option:eq(1)").val("someNewVal");
$("select option:eq(1)").text("Another Val");
$("select option:eq(1)").attr('selected', 'selected');
});
here is a working example and jquery, I am assuming you want to change the value of a select, change its text face and also have it selected at page load?
#
Attempt 2:
here is another fiddle: http://jsfiddle.net/HafLW/1/ , do you mean that you select an option, then you want to append that value to the autocomplete of a input area?
$(".document").ready(function(){
someString = "this,that";
$("input").autocomplete({source: someString.split(",")});
$("select").change(function(){
alert($(this).val()+" appended");
someString = someString+","+$(this).val();
$("input").autocomplete({source: someString.split(",")});
});
});

How do I properly create and manipulate checkboxes via javascript in Internet Explorer?

I'm writing a web app. Based on certain choices the user selects, it dynamically creates a number of checkbox input elements. For the sake of usability, they should be created in a checked state, and the user would uncheck the ones they don't want.
I have the code working fine in Firefox. Unfortunately, I have to target IE 7.0. There, I'm having no luck. Here are the relevant parts.
This creates a checkbox in the DIV box with CboxBlock for the ID.
function InsertCheckBox(name, appfk)
{
// Create the text box node.
var tbox = document.createElement('input');
// Set all the values.
tbox.type = "checkbox";
tbox.checked = "checked";
tbox.name = "cbox";
tbox.value = appfk;
// Next, we need a paragraph element to place it in.
var para = document.createElement('p');
// Text to place inside P
para.appendChild( document.createTextNode(name) );
// Append text box
para.appendChild(tbox);
// Attach to the CboxBlock
block = document.getElementById("CboxBlock");
block.appendChild( para );
}
In Firefox, this works right off the bat. The checkboxes are checked. In IE, they are not. So I added another function to fire after creation:
function SetCheckboxes()
{
block = document.getElementById("CboxBlock")
//cboxes = document.getElementsByName("cbox");
cboxes = block.childNodes;
for (ind in cboxes)
{
box = cboxes[ind];
box.checked = "checked";
}
}
I found the stupid bug where getElementsByName wasn't returning anything, but this still changes nothing. The text boxes are unchanged. I even tried changing it to box.checked = true, like I've seen in a few places, but that still didn't change it.
Can anyone see where I might be making a mistake? Is there some other way I'm supposed to manipulate checkboxes in IE? Thanks for any info you can provide.
I believe IE accesses it as an attribute, not a property.
box.setAttribute('checked', 'checked');

Categories

Resources