Reputation: 524
I think I'm really close. How can I get the "newtitle" variable to match what is typed in the Title field?
See exactly: https://jsfiddle.net/a0cj8xmy
jQuery:
var newtitle = 'This works but isn\'t what I type';
//var newtitle = $('$title-field').text(); // This doesn't work
//var newtitle = $('$title-field').html(); // This doesn't work
//var newtitle = $('$title-field').val(); // This doesn't work
$('#title-field').bind('keyup', function(){
$('#body-field').html($('#body-field').html().replace(/title=""/g,'title="'+newtitle+'"'));
});
HTML:
Title:<br>
<input type="text" id="title-field" placeholder="Type here!">
Body:<br>
<textarea id="body-field" name="body[und][0][value]" cols="60" rows="10">
<a href="" title=""><img src="" class="" /></a>
</textarea>
Upvotes: 0
Views: 62
Reputation: 885
You are not using id selector #
to get value and get value inside keyup function not outside or just not use any var for this use direct value
Also the Regular Expression will only match if the title is empty, so it has been changed to match all characters between the quotes.
var areaVal=$('#body-field').val();
$('#title-field').keyup(function(){
if($('#body-field').val().indexOf("<a")==-1)
$('#body-field').val(areaVal);
$('#body-field').val($('#body-field').val().replace(/title=".*?"/g,'title="'+$(this).val()+'"'));
});
Upvotes: 1
Reputation: 7136
After the comments we had on @ArunKumar's answer, I refactored the whole code. Also I stripped the jQuery parts :
const titleField = document.getElementById('title-field'),
bodyField = document.getElementById('body-field');
titleField.addEventListener('keyup', () => {
bodyField.value = bodyField.value.replace(/title=".*?"/g, `title="${titleField.value}"`);
})
First I save the 2 HTML elements for easier use. Then, I add the event listener, and inside the listener, I change the value of the textArea
element by replacing the relevent part.
Now you can edit the textArea inner text as you want, and you will still be able to change the title attribute (or all title
attributes, as the RegExp has the global
tag).
Edit : as from your last comment, you can add the readonly
attribute on the textArea HTML element so that it cannot be manually modified.
Upvotes: 1