Edvards Krickis Edvards Krickis - 18 days ago 6
jQuery Question

How to change text direction of textbox on radio button click?

I have this small piece of code and can't resolve problem of direction. I have text field with constant direction of left. I have 2 radio buttons Right and Left. When i click Right it shows value of Right radio button and same with Left. I want to have that when i click Right the text shows on right side of text field

dir="rtl"
and when Left clicked
dir="ltl"


Here is code

<!doctype html>
<html lang="en">
<head>
<style>
.toggler { height: 50px; position: absolute;}
.toggler2 { position: absolute;}
</style>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script>
$( function() {

$('input[name="radio-1"]').on('change', function() {

$('input[name="direction"]').val($(this).val());
});
} );
</script>
</head>
<body>

<legend>Choose direction: </legend>
<input type="radio" class="click" name="radio-1" id="radio-1" value="Right">
<label for="radio-1">Right</label>
<input type="radio" class="click" name="radio-1" id="radio-2" value="Left">
<label for="radio-2">Left</label>


<div class="toggler2">
<input type="text" name="direction">
</div>





Working code: https://jsfiddle.net/pk0vnkLn/

Answer

You can solve this by setting the dir attribute on the element based on the checked option:

$('input[name="radio-1"]').on('change', function() {
    var value = $(this).val();
    $('input[name="direction"]').val(value).attr('dir', value == 'Right' ? 'rtl' : 'ltr');
});

Updated fiddle

Comments