Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
51
rated 0 times [  58] [ 7]  / answers: 1 / hits: 34996  / 10 Years ago, wed, june 11, 2014, 12:00:00

I wrote a little piece of jQuery code below that uses the change method. I just found out jQuery is no longer being used in the project so I need to re-write the change method in Vanilla JS. Just looking for some assistance on how I can do that. Here is the code, it pulls the value of one input and enters it into another.



(function(){

$('#Email').change(function() {
$('#UserName').val($(this).val());
});

})();

More From » jquery

 Answers
4

Browsers vary on how events should be attached. You'd probably want to start with a little helper method:



function addEventHandler(elem, eventType, handler) {
if (elem.addEventListener)
elem.addEventListener (eventType, handler, false);
else if (elem.attachEvent)
elem.attachEvent ('on' + eventType, handler);
}


For the following sample, I'm going to assume that your IIFE should have really been a DOM-ready event. The IIFE in your code doesn't seem to really serve any purpose. So...



There are two events from your code, the DOM-ready event (DOMContentLoaded) and the select element's change event (onchange). Taking advantage of the above helper, your jQuery syntax translates to:



addEventHandler(document, 'DOMContentLoaded', function() {
addEventHandler(document.getElementById('Email'), 'change', function() {
document.getElementById('UserName').value = this.value;
});
});


Here's a demo:





    function addEventHandler(elem, eventType, handler) {
if (elem.addEventListener)
elem.addEventListener (eventType, handler, false);
else if (elem.attachEvent)
elem.attachEvent ('on' + eventType, handler);
}

addEventHandler(document, 'DOMContentLoaded', function() {
addEventHandler(document.getElementById('Email'), 'change', function() {
document.getElementById('UserName').value = this.value;
});
});

<select id=Email>
<option value=></option>
<option value=Test 1>Test 1</option>
<option value=Test 2>Test 2</option>
</select>

<input id=UserName type=text />




[#70610] Tuesday, June 10, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
chase

Total Points: 78
Total Questions: 106
Total Answers: 93

Location: Comoros
Member since Tue, Mar 14, 2023
1 Year ago
chase questions
Thu, Mar 31, 22, 00:00, 2 Years ago
Thu, Jul 1, 21, 00:00, 3 Years ago
Sat, Dec 12, 20, 00:00, 4 Years ago
Mon, Sep 14, 20, 00:00, 4 Years ago
;