user527892
user527892

Reputation:

Replace some text (not all) within an element

I've got a jQuery date & time picker where I've constrained the input to either 00:00 or 12:00 so I can make it work in a kind of half day/full day way. This means it fills the box with something like:

dd/mm/yy 12:00

I'd like to be able to get the contents of this field and put it in a new field in the style of:

dd/mm/yy PM

So, can I get the .val() of this text field and replace just some of the content of it, rather than all?

Upvotes: 0

Views: 105

Answers (5)

thecodeparadox
thecodeparadox

Reputation: 87073

This may work:

var v = $.trim($('input').val());
var d;
if(v == '00:00')
     d = v.replace('00:00','AM'); $('input').val(d);
if(v== '12:00')
     d = v.replace('12:00','PM');$('input').val(d); 

Upvotes: 0

Hussein
Hussein

Reputation: 42808

<input value="dd/mm/yy 12:00" />

var x = $('input').val();
var y = x.split(' ');
var z = y[0] + ' ' + (y[1] >= '12:00' ? 'PM' : 'AM');
alert(z)

Check working example at http://jsfiddle.net/aGURT/

Upvotes: 1

tiagoboldt
tiagoboldt

Reputation: 2426

When replacing the content of an element you always have to replace it all. Still, you could copy the entire element until the first blank space and then append your string..

var input = $('#yourid').text().split(' ');
var text = input[0];
/* process input[1] and add it to text */
$('#yourid').html(text).

Upvotes: 0

Silver Light
Silver Light

Reputation: 45902

Quite dirty, but should work:

var date = 'dd/mm/yy 12:00';
var splitted = date.split(' ');
var result = splitted[0] + ' ' + (splitted[1] == '12:00' ? 'PM' : 'AM');

Upvotes: 0

ThiefMaster
ThiefMaster

Reputation: 318478

You take the .val(), modify it, and then use .val(newValue) to set the new value.

To replace the time, you could use value.replace(/[0-9]+:[0-9]+$/, 'something-else')

Upvotes: 0

Related Questions