How to add attribute to class with js? - javascript

So I am trying to autofill the discount code section on a page. The class I am calling is button before. If I try to press enter it isn't applying the code, because the value wasn't saved somehow. However, filling it out manually addes this attribute to the class: after entering code manually. The site I am trying to apply discount on is luisaviaroma.com you can try the FF25 code, if you are interested in helping me with some code. I figured out that simply adding a space after the code my hand is solving the issue, is there a way to make this space press automated to (inside of js)?
function test() {
var element = document.querySelector("div[data-attribute='promo-code-input']")
var input = document.querySelector("input[name='promo-code-input']");
//element.setAttribute('class', 'InputText__baseCls___Hg_ik4cV2- InputText__focus___5q7tEpbHwI InputText__filled___1s5BW_63Y3');
element.classList.add("InputText__filled___1s5BW_63Y3");
console.log(element)
input.focus();
setTimeout(function () {
input.focus();
input.value='FF25';
let event = document.createEvent("HTMLEvents");
event.initEvent('change', true, false);
element.dispatchEvent(event);
element.blur();
}, 300)
input.select();

Although there is a KeyboardEvent the spec recommends input for text inputs.
In this case setting the bubbles attribute to true does the trick.
function test(val) {
var input = document.querySelector("input[name='promo-code-input']");
var inputEvent = new Event('input', {
bubbles: true,
})
input.focus();
input.value = val;
input.dispatchEvent(inputEvent)
console.log(input)
}

Related

Adding text to input box with jquery

I have an element on the page that looks like:
<textarea id="note-content" rows="4"></textarea>
when I try to write some jQuery to add some text to it:
$('#note-content').val('hi')
The button to "submit" the value is still greyed out.
I've tried
function setKeywordText(text) {
var el = document.getElementById("note-content");
el.value = text;
var evt = document.createEvent("Events");
evt.initEvent("change", true, true);
el.dispatchEvent(evt);
}
setKeywordText("test")
as a way to "simulate" sending keystrokes to the browser, but that doesn't seem to work either.
any thoughts?
You can do that by javascript
<script>
function changetext(){
document.getElementById("note-content").value = "hi";
}
<script>
It should def. work. Plus what exactly did you mean by browser simulation?
Am i missing something?
It appears this problem is occurring because your button is disabled.
To solve this you'd remove the disabled attribute using jQuery.fn.removeAttr, like this:
$("#button-id").removeAttr("disabled");
Add this solution it to your vanilla JavaScript code, like this:
function setKeywordText(text) {
// disable button
var btn = document.getElementById("button-id");
btn.disabled = false;
// set input value
var el = document.getElementById("note-content");
el.value = text;
// create and dispatch the event
var evt = document.createEvent("Events");
evt.initEvent("change", true, true);
el.dispatchEvent(evt);
}
// run the function
setKeywordText("test");
Good luck.

Trigger change event on hidden field when i don't know the moment of change with jQuery?

I have a hidden input in my HTML code and i want to know when the input value has changed.
<input type="hidden" id="myInputHidden" />
I can make something like this:
$('#myInputHidden').on('change', function() {
alert('triggered');
});
In the first place, this doesn't work and in many posts i have read that i must trigger manually the event.
The problem is that i don't know when (and where) the input value is changed so i cannot trigger that event.
The only way to implement a change event to a hidden field is by dirty-checking, e.g:
(function() {
var myHidden = document.getElementById('myInputHidden'),
currentValue = myHidden.value;
setTimeout(function myHiddenOnChange() {
if (myHidden.value !== currentValue) {
currentValue = myHidden.value;
myHiddenChanged.call(myHidden);
}
setTimeout(myHiddenOnChange, 30);
}, 30);
function myHiddenChanged() {
// that's your hidden field's 'change' event
}
})();
I don't recommend it, but another approach is to override the HTMLInputElement.prototype descriptor:
(function() {
var _htmlInputElementValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value'),
_htmlInputElementValueSet = _htmlInputElementValue.set,
_ev = document.createEvent('Event');
_ev.initEvent('change', true, true);
_htmlInputElementValue.set = function() {
_htmlInputElementValueSet.apply(this, [].slice.call(arguments));
if (this.type === 'hidden') {
this.dispatchEvent(_ev);
}
}
Object.defineProperty(HTMLInputElement.prototype, 'value', _htmlInputElementValue);
})();
Doing that, anytime someone changes the value property of a hidden field, it triggers the change event, so, if you're listening to that event, your code will start working.

How to press space key and then backspace key in a textarea: using JQuery?

Do we have any way to press any keyboard key in textarea using JQuery?
Usage in My Case
There are many textareas have height of 100, set by default onload (some issue with JQuery Autosize used by some developer of which i have no access to change and i am not authorized to change). There is some text displayed in textarea. If it is less say 10 character only, the height of textarea will Remain same.
Now when end user click in Textarea and then press any button to edit, then at sudden textarea gets adjusted to normal height.
So i want jquery to fire key-press(space then backspace) on load on all textareas. Do we have any way to press any keyboard key in textarea using JQuery?
You can use the trigger event. See my jsfiddle
$("textarea").each(function(){
var d = $.Event('keydown');
var e = $.Event('keydown');
d.which = 32; // space
e.which = 8; // backspace
this.focus();
this.trigger(d);
this.trigger(e);
}
Manually trigger resize:
$('textarea').each(function(){
var evt = document.createEvent('Event');
evt.initEvent('autosize:update', true, false);
$(this).dispatchEvent(evt);
});
Destroying autoresize:
$('textarea').each(function(){
var evt = document.createEvent('Event');
evt.initEvent('autosize:destroy', true, false);
$(this).dispatchEvent(evt);
});
As unable to trigger click so used following code to increase and decrease textarea:
autoHeight: function(e) {
$(e).css({'height':'auto','overflow-y':'hidden'}).height(e.scrollHeight);
},
setTimeout(function(){
$('textarea').each(function () {
kontroll.autoHeight(this);
}).on('input', function () {
kontroll.autoHeight(this);
});
}, 200);

Prevent From Writing on TextArea using Bind Event "input propertychange"

I am handling the content inside a textarea using binding a function to the event "input propertychange"
Like this:
$('#textarea').bind('input propertychange', function () {
var textarea = document.getElementById('textarea');
window.lastLineWriting = textarea.value.substr(0, textarea.value.length).split("\n").length;
var writingOnLine = textarea.value.substr(0, textarea.selectionStart).split("\n").length;
if (writingOnLine < window.lastLineWriting) {
//dont write on textarea
}
});
I don't know how to prevent the char typed by the user's keyboard to appear on the textarea... Inside that if I want to prevent the text to be inserted on textarea..
How can I do this?
you could easily stop the user from typing with this code, using jQuery:
$('textarea').bind('keypress', function (e) {
e.preventDefault();
return false;
});
NOTE:
this code will prevent the user from typing in all the textareas, to bind it specifically to one or some selected elements, you must change the selector to the desired elements.
var editable = false // Your Condition
if(editable != "true"){
$("#textarea" ).attr("disabled",true);
}

In JavaScript how to have a readonly textarea and still get onselect events?

I have noticed that if I set a textarea to 'readonly'
I no longer get onselect events.
var ta = document.createElement('textarea');
ta.readonly = true;
ta.onselect = function() { ... } // This one works only if the ta.readonly is commented out.
I need the textarea to be readonly and be notified when the user selects a certain range.
Can somebody help?
There is no straightforward way to do this by dynamically adjusting the textarea's readonly attribute onfocus, onblur, onselect, etc. while still always receiving the onselect event.
If your goal is to make sure that users cannot edit/manipulate the textarea, then I would probably just leave the textarea as non-readonly (to receive the select events) but block all user input inside of it by using preventDefault() on input events, like so:
var ta = document.createElement('textarea');
// prevent user input
ta.addEventListener('cut', function(e) { e.preventDefault(); }, false);
ta.addEventListener('copy', function(e) { e.preventDefault(); }, false);
ta.addEventListener('paste', function(e) { e.preventDefault(); }, false);
ta.addEventListener('keydown', function(e) { e.preventDefault(); }, false);
// listen for user selections
ta.addEventListener('select', function() {
// function logic...
}, false);
How about just using a <div>? You can still select text in there, and it'll be non-editable, hence readonly.
You could make a loop function that keeps checking for window text selection. If it detects that the length of the select text has reached some sort of limit it will execute what ever you see fit.
Something like this:
function getSelectedText() {
var txt = '';
if (window.getSelection) {
txt = window.getSelection();
}
else if (document.getSelection) // FireFox
{
txt = document.getSelection();
}
else if (document.selection) // IE 6/7
{
txt = document.selection.createRange().text;
}
return txt;
}
function doSomething() {
var txt = getSelectedText();
// Do something with txt variable, like txt.length
}
setInterval('doSomething()',500);
You would also need to make sure the selection is from the desired textarea.
Hopefully this will point you in the right direction.

Categories