Here is my php jquery code to generate dropdown dynamically.
It is working fine. But I have to add placeHolder in this dropdown.
So I have added below code but it is not working.
May I know where should I have add this code or something wrong with my code?
$('#calc_shipping_state').one('select2:open', function(e) {
$('input.select2-search__field').prop('placeholder', 'enter username or city');
});
Regards,
Alex
<?php
/**
* Added state filter for shipping calculater
*/
if ( 'yes' === get_option( 'wc_csz_new_state_field' ) && in_array( WC()->countries->get_base_country(), get_option( 'wc_csz_countries_codes' ) ) ) {
$country_states = [];
include( WP_PLUGIN_DIR . '/cities-shipping-zones-for-woocommerce/i18n/cities/' . WC()->countries->get_base_country() . '.php' );
woocommerce_form_field( 'calc_shipping_new_state', [
'type' => 'select',
'options' => [ '' => '' ] + apply_filters( 'csz_states', $country_states ),
'class' => [ 'form-row-wide', 'address-field' ]
] );
?>
<script type="text/javascript">
jQuery( function( $ ) {
var country = '<?php echo WC()->countries->get_base_country(); ?>';
$( document ).ready( function() { new_state_visibility() } );
function new_state_visibility() {
if ( $( '#calc_shipping_country option:selected' ).val() == country || $( '#calc_shipping_country' ).val() == country ) {
$( '#calc_shipping_new_state_field' ).show();
} else {
$( '#calc_shipping_new_state_field' ).hide();
}
};
$( '#calc_shipping_state' ).on( 'select2:open', function() {
$('.select2-search__field').attr('placeholder', 'your placeholder');
});
if ( $( '#calc_shipping_country option:selected' ).val() == country || $( '#calc_shipping_country' ).val() == country ) {
$( '#calc_shipping_state' ).data( 'select2' ).dropdown.$search.val( $( '#calc_shipping_new_state option:selected' ).text() + ' - ' );
$( '#calc_shipping_state' ).data( 'select2' ).dropdown.$search.trigger( 'input' );
$( '#calc_shipping_state' ).trigger( 'query', { term } );
}
} );
$( '#calc_shipping_state' ).on( 'select2:select', function() {
$( '#calc_shipping_new_state option' ).filter( function() { return $( this ).text() == $( '#calc_shipping_state option:selected' ).text().split( ' - ' )[0]; } ).prop( 'selected', true );
} );
$('#calc_shipping_state').one('select2:open', function(e) {
$('input.select2-search__field').prop('placeholder', 'enter username or city');
});
} );
</script>
<?php
}
?>
2
Answers
Here is the answer.
I’m not quite sure, but I think it was with
data-placeholder
attribute, so something like thisdata-placeholder="Placeholder"
You can read the documentation about placeholder’s here